File size: 3,253 Bytes
1e92f2d |
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 |
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-async-client-component'
const description = 'Prevent Client Components from being async functions.'
const message = `${description} See: ${url}`
function isCapitalized(str: string): boolean {
return /[A-Z]/.test(str?.[0])
}
export = defineRule({
meta: {
docs: {
description,
recommended: true,
url,
},
type: 'problem',
schema: [],
},
create(context) {
return {
Program(node) {
let isClientComponent: boolean = false
for (const block of node.body) {
if (
block.type === 'ExpressionStatement' &&
block.expression.type === 'Literal' &&
block.expression.value === 'use client'
) {
isClientComponent = true
}
if (block.type === 'ExportDefaultDeclaration' && isClientComponent) {
// export default async function MyComponent() {...}
if (
block.declaration?.type === 'FunctionDeclaration' &&
block.declaration.async &&
isCapitalized(block.declaration.id.name)
) {
context.report({
node: block,
message,
})
}
// async function MyComponent() {...}; export default MyComponent;
if (
block.declaration.type === 'Identifier' &&
isCapitalized(block.declaration.name)
) {
const targetName = block.declaration.name
const functionDeclaration = node.body.find((localBlock) => {
if (
localBlock.type === 'FunctionDeclaration' &&
localBlock.id.name === targetName
)
return true
if (
localBlock.type === 'VariableDeclaration' &&
localBlock.declarations.find(
(declaration) =>
declaration.id?.type === 'Identifier' &&
declaration.id.name === targetName
)
)
return true
return false
})
if (
functionDeclaration?.type === 'FunctionDeclaration' &&
functionDeclaration.async
) {
context.report({
node: functionDeclaration,
message,
})
}
if (functionDeclaration?.type === 'VariableDeclaration') {
const varDeclarator = functionDeclaration.declarations.find(
(declaration) =>
declaration.id?.type === 'Identifier' &&
declaration.id.name === targetName
)
if (
varDeclarator?.init?.type === 'ArrowFunctionExpression' &&
varDeclarator.init.async
) {
context.report({
node: functionDeclaration,
message,
})
}
}
}
}
}
},
}
},
})
|