Unverified Commit 776dca7a authored by Shu Ding's avatar Shu Ding Committed by GitHub

Improve TypeScript plugin for metadata (#45876)

This PR covers more common cases of metadata development.

<details>
  <summary>
    Invalid exports in client components
  </summary>
<img width="530" alt="CleanShot-2023-02-13-Ilq7rrRF@2x"
src="https://user-images.githubusercontent.com/3676859/218588139-0fb00d2f-1c7e-4a3e-8387-4bbb66e6a182.png">
</details>

<details>
  <summary>
    Check non-static re-assigned values
  </summary>
<img width="771" alt="CleanShot-2023-02-13-rZbmD5b6@2x"
src="https://user-images.githubusercontent.com/3676859/218588188-735b1db5-a0cc-4872-92e9-462473f2babc.png">
</details>

<details>
  <summary>
    Check re-exports, cc @leerob :D
  </summary>
<img width="819" alt="CleanShot-2023-02-13-WTzDfqIJ@2x"
src="https://user-images.githubusercontent.com/3676859/218588486-e7d04fd6-78a7-4ad4-9c77-0807b364c380.png">
</details>

## 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 512daba6
...@@ -191,6 +191,7 @@ export function createTSPlugin(modules: { ...@@ -191,6 +191,7 @@ export function createTSPlugin(modules: {
ts.forEachChild(source!, (node) => { ts.forEachChild(source!, (node) => {
if (ts.isImportDeclaration(node)) { if (ts.isImportDeclaration(node)) {
// import ...
if (isAppEntry) { if (isAppEntry) {
if (!isClientEntry) { if (!isClientEntry) {
// Check if it has valid imports in the server layer // Check if it has valid imports in the server layer
...@@ -257,6 +258,7 @@ export function createTSPlugin(modules: { ...@@ -257,6 +258,7 @@ export function createTSPlugin(modules: {
ts.isFunctionDeclaration(node) && ts.isFunctionDeclaration(node) &&
node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) node.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)
) { ) {
// export function ...
if (isAppEntry) { if (isAppEntry) {
const metadataDiagnostics = isClientEntry const metadataDiagnostics = isClientEntry
? metadata.getSemanticDiagnosticsForExportVariableStatementInClientEntry( ? metadata.getSemanticDiagnosticsForExportVariableStatementInClientEntry(
...@@ -270,7 +272,6 @@ export function createTSPlugin(modules: { ...@@ -270,7 +272,6 @@ export function createTSPlugin(modules: {
prior.push(...metadataDiagnostics) prior.push(...metadataDiagnostics)
} }
// export function ...
if (isClientEntry) { if (isClientEntry) {
prior.push( prior.push(
...clientBoundary.getSemanticDiagnosticsForFunctionExport( ...clientBoundary.getSemanticDiagnosticsForFunctionExport(
...@@ -279,6 +280,20 @@ export function createTSPlugin(modules: { ...@@ -279,6 +280,20 @@ export function createTSPlugin(modules: {
) )
) )
} }
} else if (ts.isExportDeclaration(node)) {
// export { ... }
if (isAppEntry) {
const metadataDiagnostics = isClientEntry
? metadata.getSemanticDiagnosticsForExportDeclarationInClientEntry(
fileName,
node
)
: metadata.getSemanticDiagnosticsForExportDeclaration(
fileName,
node
)
prior.push(...metadataDiagnostics)
}
} }
}) })
......
import { NEXT_TS_ERRORS } from '../constant' import { NEXT_TS_ERRORS } from '../constant'
import { getInfo, getSource, getTs, isPositionInsideNode } from '../utils' import {
getInfo,
getSource,
getTs,
getTypeChecker,
isPositionInsideNode,
} from '../utils'
const TYPE_ANOTATION = ': Metadata' const TYPE_ANOTATION = ': Metadata'
const TYPE_ANOTATION_ASYNC = ': Promise<Metadata> | Metadata' const TYPE_ANOTATION_ASYNC = ': Promise<Metadata> | Metadata'
const TYPE_IMPORT = `import type { Metadata } from 'next'` const TYPE_IMPORT = `\n\nimport type { Metadata } from 'next'`
// Find the `export const metadata = ...` node. // Find the `export const metadata = ...` node.
function getMetadataExport(fileName: string, position: number) { function getMetadataExport(fileName: string, position: number) {
...@@ -176,6 +182,37 @@ function isTyped(node: ts.VariableDeclaration | ts.FunctionDeclaration) { ...@@ -176,6 +182,37 @@ function isTyped(node: ts.VariableDeclaration | ts.FunctionDeclaration) {
return node.type !== undefined return node.type !== undefined
} }
function proxyDiagnostics(
fileName: string,
pos: number[],
n: ts.VariableDeclaration | ts.FunctionDeclaration
) {
// Get diagnostics
const { languageService } = getProxiedLanguageService()
const diagnostics = languageService.getSemanticDiagnostics(fileName)
const source = getSource(fileName)
// Filter and map the results
return diagnostics
.filter((d) => {
if (d.start === undefined || d.length === undefined) return false
if (d.start < n.getFullStart()) return false
if (d.start + d.length >= n.getFullStart() + n.getFullWidth() + pos[1])
return false
return true
})
.map((d) => {
return {
file: source,
category: d.category,
code: d.code,
messageText: d.messageText,
start: d.start! < pos[0] ? d.start : d.start! - pos[1],
length: d.length,
}
})
}
const metadata = { const metadata = {
filterCompletionsAtPosition( filterCompletionsAtPosition(
fileName: string, fileName: string,
...@@ -284,41 +321,8 @@ const metadata = { ...@@ -284,41 +321,8 @@ const metadata = {
fileName: string, fileName: string,
node: ts.VariableStatement | ts.FunctionDeclaration node: ts.VariableStatement | ts.FunctionDeclaration
) { ) {
const source = getSource(fileName)
const ts = getTs() const ts = getTs()
function proxyDiagnostics(
pos: number[],
n: ts.VariableDeclaration | ts.FunctionDeclaration
) {
// Get diagnostics
const { languageService } = getProxiedLanguageService()
const diagnostics = languageService.getSemanticDiagnostics(fileName)
// Filter and map the results
return diagnostics
.filter((d) => {
if (d.start === undefined || d.length === undefined) return false
if (d.start < n.getFullStart()) return false
if (
d.start + d.length >=
n.getFullStart() + n.getFullWidth() + pos[1]
)
return false
return true
})
.map((d) => {
return {
file: source,
category: d.category,
code: d.code,
messageText: d.messageText,
start: d.start! < pos[0] ? d.start : d.start! - pos[1],
length: d.length,
}
})
}
if (ts.isFunctionDeclaration(node)) { if (ts.isFunctionDeclaration(node)) {
if (node.name?.getText() === 'generateMetadata') { if (node.name?.getText() === 'generateMetadata') {
if (isTyped(node)) return [] if (isTyped(node)) return []
...@@ -327,7 +331,7 @@ const metadata = { ...@@ -327,7 +331,7 @@ const metadata = {
const pos = updateVirtualFileWithType(fileName, node, true) const pos = updateVirtualFileWithType(fileName, node, true)
if (!pos) return [] if (!pos) return []
return proxyDiagnostics(pos, node) return proxyDiagnostics(fileName, pos, node)
} }
} else { } else {
for (const declaration of node.declarationList.declarations) { for (const declaration of node.declarationList.declarations) {
...@@ -338,13 +342,104 @@ const metadata = { ...@@ -338,13 +342,104 @@ const metadata = {
const pos = updateVirtualFileWithType(fileName, declaration) const pos = updateVirtualFileWithType(fileName, declaration)
if (!pos) break if (!pos) break
return proxyDiagnostics(pos, declaration) return proxyDiagnostics(fileName, pos, declaration)
} }
} }
} }
return [] return []
}, },
getSemanticDiagnosticsForExportDeclarationInClientEntry(
fileName: string,
node: ts.ExportDeclaration
) {
const ts = getTs()
const source = getSource(fileName)
const diagnostics: ts.Diagnostic[] = []
const exportClause = node.exportClause
if (exportClause && ts.isNamedExports(exportClause)) {
for (const e of exportClause.elements) {
if (['generateMetadata', 'metadata'].includes(e.name.getText())) {
diagnostics.push({
file: source,
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,
messageText: `The Next.js '${e.name.getText()}' API is not allowed in a client component.`,
start: e.name.getStart(),
length: e.name.getWidth(),
})
}
}
}
return diagnostics
},
getSemanticDiagnosticsForExportDeclaration(
fileName: string,
node: ts.ExportDeclaration
) {
const ts = getTs()
const exportClause = node.exportClause
if (exportClause && ts.isNamedExports(exportClause)) {
for (const e of exportClause.elements) {
if (e.name.getText() === 'metadata') {
// Get the original declaration node of element
const typeChecker = getTypeChecker()
if (typeChecker) {
const symbol = typeChecker.getSymbolAtLocation(e.name)
if (symbol) {
const metadataSymbol = typeChecker.getAliasedSymbol(symbol)
if (metadataSymbol && metadataSymbol.declarations) {
const declaration = metadataSymbol.declarations[0]
if (declaration && ts.isVariableDeclaration(declaration)) {
if (isTyped(declaration)) break
const declarationFileName =
declaration.getSourceFile().fileName
const isSameFile = declarationFileName === fileName
// We annotate with the type in a vritual language service
const pos = updateVirtualFileWithType(
declarationFileName,
declaration
)
if (!pos) break
const diagnostics = proxyDiagnostics(
declarationFileName,
pos,
declaration
)
if (diagnostics.length) {
if (isSameFile) {
return diagnostics
} else {
return [
{
file: getSource(fileName),
category: ts.DiagnosticCategory.Error,
code: NEXT_TS_ERRORS.INVALID_METADATA_EXPORT,
messageText: `The 'metadata' export value is not typed correctly, please make sure it is typed as 'Metadata':\nhttps://beta.nextjs.org/docs/guides/seo#static-metadata`,
start: e.name.getStart(),
length: e.name.getWidth(),
},
]
}
}
}
}
}
}
}
}
}
return []
},
getCompletionEntryDetails( getCompletionEntryDetails(
fileName: string, fileName: string,
position: number, position: number,
......
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