Skip to content

Draft:Add new vue/require-mayberef-unwrap rule #2798

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/happy-corners-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'eslint-plugin-vue': minor
---

Added new [`vue/require-mayberef-unwrap`](https://eslint.vuejs.org/rules/require-mayberef-unwrap.html) rule
2 changes: 2 additions & 0 deletions docs/rules/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ Rules in this category are enabled for all presets provided by eslint-plugin-vue
| [vue/no-watch-after-await] | disallow asynchronously registered `watch` | | :three::hammer: |
| [vue/prefer-import-from-vue] | enforce import from 'vue' instead of import from '@vue/*' | :wrench: | :three::hammer: |
| [vue/require-component-is] | require `v-bind:is` of `<component>` elements | | :three::two::warning: |
| [vue/require-mayberef-unwrap] | require unwrapping `MaybeRef` values with `unref()` in conditions | :wrench: | :three::warning: |
| [vue/require-prop-type-constructor] | require prop type to be a constructor | :wrench: | :three::two::hammer: |
| [vue/require-render-return] | enforce render function to always return value | | :three::two::warning: |
| [vue/require-slots-as-functions] | enforce properties of `$slots` to be used as a function | | :three::warning: |
Expand Down Expand Up @@ -564,6 +565,7 @@ The following rules extend the rules provided by ESLint itself and apply them to
[vue/require-explicit-slots]: ./require-explicit-slots.md
[vue/require-expose]: ./require-expose.md
[vue/require-macro-variable-name]: ./require-macro-variable-name.md
[vue/require-mayberef-unwrap]: ./require-mayberef-unwrap.md
[vue/require-name-property]: ./require-name-property.md
[vue/require-prop-comment]: ./require-prop-comment.md
[vue/require-prop-type-constructor]: ./require-prop-type-constructor.md
Expand Down
72 changes: 72 additions & 0 deletions docs/rules/require-mayberef-unwrap.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
pageClass: rule-details
sidebarDepth: 0
title: vue/require-mayberef-unwrap
description: require `MaybeRef` values to be unwrapped with `unref()` before using in conditions
since: v10.3.0
---

# vue/require-mayberef-unwrap

> require unwrapping `MaybeRef` values with `unref()` in conditions

- :gear: This rule is included in all of `"plugin:vue/essential"`, `*.configs["flat/essential"]`, `"plugin:vue/strongly-recommended"`, `*.configs["flat/strongly-recommended"]`, `"plugin:vue/recommended"` and `*.configs["flat/recommended"]`.
- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fix-problems) can automatically fix some of the problems reported by this rule.

## :book: Rule Details

This rule reports cases where a `MaybeRef` value is used incorrectly in conditions.
You must use `unref()` to access the inner value.

<eslint-code-block fix :rules="{'vue/require-mayberef-unwrap': ['error']}">

```vue
<script lang="ts">
import { ref, unref, type MaybeRef } from 'vue'

export default {
setup() {
const maybeRef: MaybeRef<boolean> = ref(false)

/* ✓ GOOD */
if (unref(maybeRef)) {
console.log('good')
}
const result = unref(maybeRef) ? 'true' : 'false'

/* ✗ BAD */
if (maybeRef) {
console.log('bad')
}
const alt = maybeRef ? 'true' : 'false'

return {
maybeRef
}
}
}
</script>
```

</eslint-code-block>

## :wrench: Options

Nothing.

This rule also applies to `MaybeRefOrGetter` values in addition to `MaybeRef`.

## :books: Further Reading

- [Guide – Reactivity – `unref`](https://vuejs.org/guide/essentials/reactivity-fundamentals.html#unref)
- [API – `MaybeRef`](https://vuejs.org/api/utility-types.html#mayberef)
- [API – `MaybeRefOrGetter`](https://vuejs.org/api/utility-types.html#maybereforgetter)

## :rocket: Version

This rule was introduced in eslint-plugin-vue v10.3.0

## :mag: Implementation

- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/require-mayberef-unwrap.js)
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/require-mayberef-unwrap.js)
1 change: 1 addition & 0 deletions lib/configs/flat/vue3-essential.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ module.exports = [
'vue/no-watch-after-await': 'error',
'vue/prefer-import-from-vue': 'error',
'vue/require-component-is': 'error',
'vue/require-mayberef-unwrap': 'error',
'vue/require-prop-type-constructor': 'error',
'vue/require-render-return': 'error',
'vue/require-slots-as-functions': 'error',
Expand Down
1 change: 1 addition & 0 deletions lib/configs/vue3-essential.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ module.exports = {
'vue/no-watch-after-await': 'error',
'vue/prefer-import-from-vue': 'error',
'vue/require-component-is': 'error',
'vue/require-mayberef-unwrap': 'error',
'vue/require-prop-type-constructor': 'error',
'vue/require-render-return': 'error',
'vue/require-slots-as-functions': 'error',
Expand Down
1 change: 1 addition & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,7 @@ const plugin = {
'require-explicit-slots': require('./rules/require-explicit-slots'),
'require-expose': require('./rules/require-expose'),
'require-macro-variable-name': require('./rules/require-macro-variable-name'),
'require-mayberef-unwrap': require('./rules/require-mayberef-unwrap'),
'require-name-property': require('./rules/require-name-property'),
'require-prop-comment': require('./rules/require-prop-comment'),
'require-prop-type-constructor': require('./rules/require-prop-type-constructor'),
Expand Down
278 changes: 278 additions & 0 deletions lib/rules/require-mayberef-unwrap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,278 @@
/**
* @author 2nofa11
* See LICENSE file in root directory for full license.
*/
'use strict'

const utils = require('../utils')

/**
* Check TypeScript type node for MaybeRef/MaybeRefOrGetter
* @param {import('@typescript-eslint/types').TSESTree.TypeNode | undefined} typeNode
* @returns {boolean}
*/
function isMaybeRefTypeNode(typeNode) {
if (!typeNode) return false
if (
typeNode.type === 'TSTypeReference' &&
typeNode.typeName &&
typeNode.typeName.type === 'Identifier'
) {
return (
typeNode.typeName.name === 'MaybeRef' ||
typeNode.typeName.name === 'MaybeRefOrGetter'
)
}
if (typeNode.type === 'TSUnionType') {
return typeNode.types.some((t) => isMaybeRefTypeNode(t))
}
return false
}

module.exports = {
meta: {
type: 'problem',
docs: {
description:
'require `MaybeRef` values to be unwrapped with `unref()` before using in conditions',
categories: undefined,
url: 'https://eslint.vuejs.org/rules/require-mayberef-unwrap.html'
},
fixable: 'code',
schema: [],
messages: {
requireUnref:
'MaybeRef should be unwrapped with `unref()` before using in conditions. Use `unref({{name}})` instead.'
}
},
/** @param {RuleContext} context */
create(context) {
const filename = context.getFilename()
if (!utils.isVueFile(filename) && !utils.isTypeScriptFile(filename)) {
return {}
}

/** @type {Map<string, Set<string>>} */
const maybeRefPropsMap = new Map()

/**
* Determine if identifier should be considered MaybeRef
* @param {Identifier} node
*/
function isMaybeRef(node) {
const variable = utils.findVariableByIdentifier(context, node)
if (!variable) {
return false
}

const definition = variable.defs[0]
if (definition.type !== 'Variable') {
return false
}

const id = definition.node?.id
if (!id || id.type !== 'Identifier' || !id.typeAnnotation) {
return false
}

return isMaybeRefTypeNode(id.typeAnnotation.typeAnnotation)
}

/**
* Check if MemberExpression accesses a MaybeRef prop
* @param {Identifier} objectNode
* @param {string} propertyName
*/
function isMaybeRefPropsAccess(objectNode, propertyName) {
if (!propertyName) {
return false
}

const variable = utils.findVariableByIdentifier(context, objectNode)
if (!variable) {
return false
}

const maybeRefProps = maybeRefPropsMap.get(variable.name)
return maybeRefProps ? maybeRefProps.has(propertyName) : false
}

/**
* Reports if the identifier is a MaybeRef type
* @param {Identifier} node
* @param {string} [customName] Custom name for error message
*/
function reportIfMaybeRef(node, customName) {
if (!isMaybeRef(node)) {
return
}

const sourceCode = context.getSourceCode()
context.report({
node,
messageId: 'requireUnref',
data: { name: customName || node.name },
fix(fixer) {
return fixer.replaceText(node, `unref(${sourceCode.getText(node)})`)
}
})
}

/**
* Reports if the MemberExpression accesses a MaybeRef prop
* @param {MemberExpression} node
*/
function reportIfMaybeRefProps(node) {
if (node.object.type !== 'Identifier') {
return
}

const propertyName = utils.getStaticPropertyName(node)
if (!propertyName) {
return
}

if (!isMaybeRefPropsAccess(node.object, propertyName)) {
return
}

const sourceCode = context.getSourceCode()
context.report({
node: node.property,
messageId: 'requireUnref',
data: { name: `${node.object.name}.${propertyName}` },
fix(fixer) {
return fixer.replaceText(node, `unref(${sourceCode.getText(node)})`)
}
})
}

return utils.compositingVisitors(
{
// if (maybeRef)
/** @param {Identifier} node */
'IfStatement>Identifier'(node) {
reportIfMaybeRef(node)
},
// maybeRef ? x : y
/** @param {Identifier & {parent: ConditionalExpression}} node */
'ConditionalExpression>Identifier'(node) {
if (node.parent.test !== node) {
return
}
reportIfMaybeRef(node)
},
// !maybeRef, +maybeRef, -maybeRef, ~maybeRef, typeof maybeRef
/** @param {Identifier} node */
'UnaryExpression>Identifier'(node) {
reportIfMaybeRef(node)
},
// maybeRef || other, maybeRef && other, maybeRef ?? other
/** @param {Identifier & {parent: LogicalExpression}} node */
'LogicalExpression>Identifier'(node) {
reportIfMaybeRef(node)
},
// maybeRef == x, maybeRef != x, maybeRef === x, maybeRef !== x
/** @param {Identifier} node */
'BinaryExpression>Identifier'(node) {
reportIfMaybeRef(node)
},
// Boolean(maybeRef), String(maybeRef)
/** @param {Identifier} node */
'CallExpression>Identifier'(node) {
const parent = node.parent
if (parent?.type !== 'CallExpression') return

const callee = parent.callee
if (callee?.type !== 'Identifier') return

if (!['Boolean', 'String'].includes(callee.name)) return

if (parent.arguments[0] === node) {
reportIfMaybeRef(node)
}
},
// props.maybeRefProp
/** @param {MemberExpression} node */
MemberExpression(node) {
reportIfMaybeRefProps(node)
}
},
utils.defineScriptSetupVisitor(context, {
onDefinePropsEnter(node, props) {
if (
!node.parent ||
node.parent.type !== 'VariableDeclarator' ||
node.parent.init !== node
) {
return
}

const propsParam = node.parent.id
if (propsParam.type !== 'Identifier') {
return
}

const maybeRefProps = new Set()
for (const prop of props) {
if (prop.type !== 'type' || !prop.node) {
continue
}

if (
prop.node.type !== 'TSPropertySignature' ||
!prop.node.typeAnnotation
) {
continue
}

const typeAnnotation = prop.node.typeAnnotation.typeAnnotation
if (isMaybeRefTypeNode(typeAnnotation)) {
maybeRefProps.add(prop.propName)
}
}

if (maybeRefProps.size > 0) {
maybeRefPropsMap.set(propsParam.name, maybeRefProps)
}
}
}),
utils.defineVueVisitor(context, {
onSetupFunctionEnter(node) {
const propsParam = utils.skipDefaultParamValue(node.params[0])
if (!propsParam || propsParam.type !== 'Identifier') {
return
}

if (!propsParam.typeAnnotation) {
return
}

const typeAnnotation = propsParam.typeAnnotation.typeAnnotation
const maybeRefProps = new Set()

if (typeAnnotation.type === 'TSTypeLiteral') {
for (const member of typeAnnotation.members) {
if (
member.type === 'TSPropertySignature' &&
member.key &&
member.key.type === 'Identifier' &&
member.typeAnnotation &&
isMaybeRefTypeNode(member.typeAnnotation.typeAnnotation)
) {
maybeRefProps.add(member.key.name)
}
}
}

if (maybeRefProps.size > 0) {
maybeRefPropsMap.set(propsParam.name, maybeRefProps)
}
},
onVueObjectExit() {
maybeRefPropsMap.clear()
}
})
)
}
}
Loading