Unverified Commit b8b13af1 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Refactor TS plugin code structure (#45375)

This PR mainly refactors the TS plugin structure and moves things over the typescript/ folder under server/. I created a rules/ folder to separate different kinds of insights, current it covers:
- Intellisense for entries on the server layer:
  - Hide autocompletions for disallowed APIs such as `useState`
  - Show errors if these are used
- Intellisense for all entires:
  - Prop hints such as `params` and `searchParams` for pages, and named slots for layouts
  - Error for invalid props
- Intellisense for exported configs:
  - Autocompletion and docs for configs
  - Hover hints for configs
  - Error for invalid configs and extra exports
- Intellisense for client boundary modules
  - Warn if `"use client"` isn't on the top of other expressions
  - (**new**) Error for unserializable props passed to exported functions

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] [e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see [`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 3421b482
This diff is collapsed.
export const NEXT_TS_ERRORS = {
INVALID_SERVER_API: 71001,
INVALID_ENTRY_EXPORT: 71002,
INVALID_OPTION_VALUE: 71003,
MISPLACED_CLIENT_ENTRY: 71004,
INVALID_PAGE_PROP: 71005,
INVALID_CONFIG_OPTION: 71006,
INVALID_CLIENT_ENTRY_PROP: 71007,
}
export const ALLOWED_EXPORTS = [
'config',
'generateStaticParams',
'metadata',
'generateMetadata',
]
export const LEGACY_CONFIG_EXPORT = 'config'
export const DISALLOWED_SERVER_REACT_APIS: string[] = [
'useState',
'useEffect',
'useLayoutEffect',
'useDeferredValue',
'useImperativeHandle',
'useInsertionEffect',
'useReducer',
'useRef',
'useSyncExternalStore',
'useTransition',
'Component',
'PureComponent',
'createContext',
'createFactory',
]
export const ALLOWED_PAGE_PROPS = ['params', 'searchParams']
export const ALLOWED_LAYOUT_PROPS = ['params', 'children']
/**
* This is a TypeScript language service plugin for Next.js app directory,
* it provides the following features:
*
* - Warns about disallowed React APIs in server components.
* - Warns about disallowed layout and page exports.
* - Autocompletion for entry configurations.
* - Hover hint and docs for entry configurations.
*/
import {
init,
getIsClientEntry,
isAppEntryFile,
isDefaultFunctionExport,
isPositionInsideNode,
getSource,
} from './utils'
import { NEXT_TS_ERRORS } from './constant'
import entryConfig from './rules/config'
import serverLayer from './rules/server'
import entryDefault from './rules/entry'
import clientBoundary from './rules/client-boundary'
export function createTSPlugin(modules: {
typescript: typeof import('typescript/lib/tsserverlibrary')
}) {
const ts = modules.typescript
function create(info: ts.server.PluginCreateInfo) {
init({
ts,
info,
})
// Set up decorator object
const proxy = Object.create(null)
for (let k of Object.keys(info.languageService)) {
const x = (info.languageService as any)[k]
proxy[k] = (...args: Array<{}>) => x.apply(info.languageService, args)
}
// Auto completion
proxy.getCompletionsAtPosition = (
fileName: string,
position: number,
options: any
) => {
let prior = info.languageService.getCompletionsAtPosition(
fileName,
position,
options
) || {
isGlobalCompletion: false,
isMemberCompletion: false,
isNewIdentifierLocation: false,
entries: [],
}
if (!isAppEntryFile(fileName)) return prior
// Remove specified entries from completion list if it's a server entry.
if (!getIsClientEntry(fileName)) {
prior.entries = serverLayer.filterCompletionsAtPosition(prior.entries)
}
// Add auto completions for export configs.
const entries = entryConfig.getCompletionsAtPosition(fileName, position)
prior.entries = [...prior.entries, ...entries]
const source = getSource(fileName)
if (!source) return prior
ts.forEachChild(source!, (node) => {
// Auto completion for default export function's props.
if (
isPositionInsideNode(position, node) &&
isDefaultFunctionExport(node)
) {
prior.entries.push(
...entryDefault.getCompletionsAtPosition(
fileName,
node as ts.FunctionDeclaration,
position
)
)
}
})
return prior
}
// Show auto completion details
proxy.getCompletionEntryDetails = (
fileName: string,
position: number,
entryName: string,
formatOptions: ts.FormatCodeOptions,
source: string,
preferences: ts.UserPreferences,
data: ts.CompletionEntryData
) => {
const entryCompletionEntryDetails = entryConfig.getCompletionEntryDetails(
entryName,
data
)
if (entryCompletionEntryDetails) return entryCompletionEntryDetails
return info.languageService.getCompletionEntryDetails(
fileName,
position,
entryName,
formatOptions,
source,
preferences,
data
)
}
// Quick info
proxy.getQuickInfoAtPosition = (fileName: string, position: number) => {
const prior = info.languageService.getQuickInfoAtPosition(
fileName,
position
)
if (!isAppEntryFile(fileName)) return prior
// Remove type suggestions for disallowed APIs in server components.
if (!getIsClientEntry(fileName)) {
const definitions = info.languageService.getDefinitionAtPosition(
fileName,
position
)
if (
definitions &&
serverLayer.hasDisallowedReactAPIDefinition(definitions)
) {
return
}
}
const overriden = entryConfig.getQuickInfoAtPosition(fileName, position)
if (overriden) return overriden
return prior
}
// Show errors for disallowed imports
proxy.getSemanticDiagnostics = (fileName: string) => {
const prior = info.languageService.getSemanticDiagnostics(fileName)
const source = getSource(fileName)
if (!source) return prior
let isClientEntry = false
const isAppEntry = isAppEntryFile(fileName)
try {
isClientEntry = getIsClientEntry(fileName, true)
} catch (e: any) {
prior.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.MISPLACED_CLIENT_ENTRY,
...e,
})
isClientEntry = false
}
ts.forEachChild(source!, (node) => {
if (ts.isImportDeclaration(node)) {
if (isAppEntry) {
if (!isClientEntry) {
// Check if it has valid imports in the server layer
const diagnostics =
serverLayer.getSemanticDiagnosticsForImportDeclaration(
source,
node
)
prior.push(...diagnostics)
}
}
} else if (
ts.isVariableStatement(node) &&
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
) {
// export const ...
if (isAppEntry) {
// Check if it has correct option exports
const diagnostics =
entryConfig.getSemanticDiagnosticsForExportVariableStatement(
source,
node
)
prior.push(...diagnostics)
}
if (isClientEntry) {
prior.push(
...clientBoundary.getSemanticDiagnosticsForExportVariableStatement(
source,
node
)
)
}
} else if (isDefaultFunctionExport(node)) {
// export default function ...
if (isAppEntry) {
const diagnostics = entryDefault.getSemanticDiagnostics(
fileName,
source,
node
)
prior.push(...diagnostics)
}
if (isClientEntry) {
prior.push(
...clientBoundary.getSemanticDiagnosticsForFunctionExport(
source,
node
)
)
}
} else if (
ts.isFunctionDeclaration(node) &&
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
) {
// export function ...
if (isClientEntry) {
prior.push(
...clientBoundary.getSemanticDiagnosticsForFunctionExport(
source,
node
)
)
}
}
})
return prior
}
return proxy
}
return { create }
}
// This module provides intellisense for all components that has the `"use client"` directive.
import { NEXT_TS_ERRORS } from '../constant'
import { getTs, getTypeChecker } from '../utils'
const clientBoundary = {
getSemanticDiagnosticsForExportVariableStatement(
source: ts.SourceFile,
node: ts.VariableStatement
) {
const ts = getTs()
const diagnostics: ts.Diagnostic[] = []
if (ts.isVariableDeclarationList(node.declarationList)) {
for (const declaration of node.declarationList.declarations) {
const initializer = declaration.initializer
if (initializer && ts.isArrowFunction(initializer)) {
diagnostics.push(
...clientBoundary.getSemanticDiagnosticsForFunctionExport(
source,
initializer
)
)
}
}
}
return diagnostics
},
getSemanticDiagnosticsForFunctionExport(
source: ts.SourceFile,
node: ts.FunctionDeclaration | ts.ArrowFunction
) {
const ts = getTs()
const typeChecker = getTypeChecker()
if (!typeChecker) return []
const diagnostics: ts.Diagnostic[] = []
const props = node.parameters?.[0]?.name
if (props && ts.isObjectBindingPattern(props)) {
for (const prop of (props as ts.ObjectBindingPattern).elements) {
const type = typeChecker.getTypeAtLocation(prop)
const typeDeclarationNode = type.symbol?.getDeclarations()?.[0]
const propName = (prop.propertyName || prop.name).getText()
if (typeDeclarationNode) {
if (
// Show errors for not serializable props.
ts.isFunctionOrConstructorTypeNode(typeDeclarationNode) ||
ts.isClassDeclaration(typeDeclarationNode)
) {
diagnostics.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_CLIENT_ENTRY_PROP,
messageText: `All props must be serializable for client components in the entry file, "${propName}" is invalid.`,
start: prop.getStart(),
length: prop.getWidth(),
})
}
}
}
}
return diagnostics
},
}
export default clientBoundary
This diff is collapsed.
import path from 'path'
import fs from 'fs'
import {
ALLOWED_LAYOUT_PROPS,
ALLOWED_PAGE_PROPS,
NEXT_TS_ERRORS,
} from '../constant'
import { getTs, isPageFile, isPositionInsideNode } from '../utils'
const entry = {
// Give auto completion for the component's props
getCompletionsAtPosition(
fileName: string,
node: ts.FunctionDeclaration,
position: number
) {
const ts = getTs()
const entries: ts.CompletionEntry[] = []
// Default export function might not accept parameters
const paramNode = node.parameters?.[0] as
| ts.ParameterDeclaration
| undefined
if (paramNode && isPositionInsideNode(position, paramNode)) {
const props = paramNode?.name
if (props && ts.isObjectBindingPattern(props)) {
let validProps = []
let validPropsWithType = []
let type: string
if (isPageFile(fileName)) {
// For page entries (page.js), it can only have `params` and `searchParams`
// as the prop names.
validProps = ALLOWED_PAGE_PROPS
validPropsWithType = ALLOWED_PAGE_PROPS
type = 'page'
} else {
// For layout entires, check if it has any named slots.
const currentDir = path.dirname(fileName)
const items = fs.readdirSync(currentDir, {
withFileTypes: true,
})
const slots = []
for (const item of items) {
if (item.isDirectory() && item.name.startsWith('@')) {
slots.push(item.name.slice(1))
}
}
validProps = ALLOWED_LAYOUT_PROPS.concat(slots)
validPropsWithType = ALLOWED_LAYOUT_PROPS.concat(
slots.map((s) => `${s}: React.ReactNode`)
)
type = 'layout'
}
// Auto completion for props
for (const element of props.elements) {
if (isPositionInsideNode(position, element)) {
const nameNode = element.propertyName || element.name
if (isPositionInsideNode(position, nameNode)) {
for (const name of validProps) {
entries.push({
name,
insertText: name,
sortText: '_' + name,
kind: ts.ScriptElementKind.memberVariableElement,
kindModifiers: ts.ScriptElementKindModifier.none,
labelDetails: {
description: `Next.js ${type} prop`,
},
} as ts.CompletionEntry)
}
}
break
}
}
// Auto completion for types
if (paramNode.type && ts.isTypeLiteralNode(paramNode.type)) {
for (const member of paramNode.type.members) {
if (isPositionInsideNode(position, member)) {
for (const name of validPropsWithType) {
entries.push({
name,
insertText: name,
sortText: '_' + name,
kind: ts.ScriptElementKind.memberVariableElement,
kindModifiers: ts.ScriptElementKindModifier.none,
labelDetails: {
description: `Next.js ${type} prop type`,
},
} as ts.CompletionEntry)
}
break
}
}
}
}
}
return entries
},
// Give error diagnostics for the component
getSemanticDiagnostics(
fileName: string,
source: ts.SourceFile,
node: ts.FunctionDeclaration
) {
const ts = getTs()
let validProps = []
let type: string
if (isPageFile(fileName)) {
// For page entries (page.js), it can only have `params` and `searchParams`
// as the prop names.
validProps = ALLOWED_PAGE_PROPS
type = 'page'
} else {
// For layout entires, check if it has any named slots.
const currentDir = path.dirname(fileName)
const items = fs.readdirSync(currentDir, { withFileTypes: true })
const slots = []
for (const item of items) {
if (item.isDirectory() && item.name.startsWith('@')) {
slots.push(item.name.slice(1))
}
}
validProps = ALLOWED_LAYOUT_PROPS.concat(slots)
type = 'layout'
}
const diagnostics: ts.Diagnostic[] = []
const props = node.parameters?.[0]?.name
if (props && ts.isObjectBindingPattern(props)) {
for (const prop of (props as ts.ObjectBindingPattern).elements) {
const propName = (prop.propertyName || prop.name).getText()
if (!validProps.includes(propName)) {
diagnostics.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_PAGE_PROP,
messageText: `"${propName}" is not a valid ${type} prop.`,
start: prop.getStart(),
length: prop.getWidth(),
})
}
}
}
return diagnostics
},
}
export default entry
import { DISALLOWED_SERVER_REACT_APIS, NEXT_TS_ERRORS } from '../constant'
import { getTs } from '../utils'
const serverLayer = {
// On the server layer we need to filter out some invalid completion results.
filterCompletionsAtPosition(entries: ts.CompletionEntry[]) {
return entries.filter((e: ts.CompletionEntry) => {
// Remove disallowed React APIs.
if (
DISALLOWED_SERVER_REACT_APIS.includes(e.name) &&
e.kindModifiers === 'declare'
) {
return false
}
return true
})
},
// Filter out quick info for some React APIs.
hasDisallowedReactAPIDefinition(definitions: readonly ts.DefinitionInfo[]) {
return definitions?.some(
(d) =>
DISALLOWED_SERVER_REACT_APIS.includes(d.name) &&
d.containerName === 'React'
)
},
// Give errors about disallowed imports such as `useState`.
getSemanticDiagnosticsForImportDeclaration(
source: ts.SourceFile,
node: ts.ImportDeclaration
) {
const ts = getTs()
const diagnostics: ts.Diagnostic[] = []
const importPath = node.moduleSpecifier.getText(source!)
if (importPath === "'react'" || importPath === '"react"') {
// Check if it imports "useState"
const importClause = node.importClause
if (importClause) {
const namedBindings = importClause.namedBindings
if (namedBindings && ts.isNamedImports(namedBindings)) {
const elements = namedBindings.elements
for (const element of elements) {
const name = element.name.getText(source!)
if (DISALLOWED_SERVER_REACT_APIS.includes(name)) {
diagnostics.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_SERVER_API,
messageText: `"${name}" is not allowed in Server Components.`,
start: element.name.getStart(),
length: element.name.getWidth(),
})
}
}
}
}
}
return diagnostics
},
}
export default serverLayer
import path from 'path'
type TypeScript = typeof import('typescript/lib/tsserverlibrary')
let ts: TypeScript
let info: ts.server.PluginCreateInfo
let appDirRegExp: RegExp
export function log(message: string) {
info.project.projectService.logger.info(message)
}
// This function has to be called initially.
export function init(opts: {
ts: TypeScript
info: ts.server.PluginCreateInfo
}) {
ts = opts.ts
info = opts.info
const projectDir = info.project.getCurrentDirectory()
appDirRegExp = new RegExp(
'^' + (projectDir + '(/src)?/app').replace(/[\\/]/g, '[\\/]')
)
log('Starting Next.js TypeScript plugin: ' + projectDir)
}
export function getTs() {
return ts
}
export function getTypeChecker() {
return info.languageService.getProgram()?.getTypeChecker()
}
export function getSource(fileName: string) {
return info.languageService.getProgram()?.getSourceFile(fileName)
}
export function removeStringQuotes(str: string): string {
return str.replace(/^['"`]|['"`]$/g, '')
}
export const isPositionInsideNode = (position: number, node: ts.Node) => {
const start = node.getFullStart()
return start <= position && position <= node.getFullWidth() + start
}
export const isDefaultFunctionExport = (
node: ts.Node
): node is ts.FunctionDeclaration => {
if (ts.isFunctionDeclaration(node)) {
let hasExportKeyword = false
let hasDefaultKeyword = false
if (node.modifiers) {
for (const modifier of node.modifiers) {
if (modifier.kind === ts.SyntaxKind.ExportKeyword) {
hasExportKeyword = true
} else if (modifier.kind === ts.SyntaxKind.DefaultKeyword) {
hasDefaultKeyword = true
}
}
}
// `export default function`
if (hasExportKeyword && hasDefaultKeyword) {
return true
}
}
return false
}
export const isAppEntryFile = (filePath: string) => {
return (
appDirRegExp.test(filePath) &&
/^(page|layout)\.(mjs|js|jsx|ts|tsx)$/.test(path.basename(filePath))
)
}
export const isPageFile = (filePath: string) => {
return (
appDirRegExp.test(filePath) &&
/^page\.(mjs|js|jsx|ts|tsx)$/.test(path.basename(filePath))
)
}
// Check if a module is a client entry.
export function getIsClientEntry(
fileName: string,
throwOnInvalidDirective?: boolean
) {
const source = info.languageService.getProgram()?.getSourceFile(fileName)
if (source) {
let isClientEntry = false
let isDirective = true
ts.forEachChild(source!, (node) => {
if (
ts.isExpressionStatement(node) &&
ts.isStringLiteral(node.expression)
) {
if (node.expression.text === 'use client') {
if (isDirective) {
isClientEntry = true
} else {
if (throwOnInvalidDirective) {
const e = {
messageText:
'The `"use client"` directive must be put at the top of the file.',
start: node.expression.getStart(),
length: node.expression.getWidth(),
}
throw e
}
}
}
} else {
isDirective = false
}
})
return isClientEntry
}
return false
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment