Unverified Commit 2c672c1d authored by Sukka's avatar Sukka Committed by GitHub

refactor: migrate `eslint-plugin-next` to typescript (#41046)

In #38647, @balazsorban44 has migrated the rule `no-img-element` to
typescript. The PR follows #38647 by migrating the entire
`eslint-plugin-next` to use typescript. Note it is still possible to
write new rules in javascript.

The PR does the following things:

- Migrates all `utils` to typescript
  - All previous JSDoc are also converted to the type definitions
- Creates a utility method `defineRule`
  - This is a stub function to provide the type check ability.
- With the `defineRule` we don't have to tediously import type
definition `Rule.RuleMetaData` and `Rule.RuleModule['create']` from
`eslint` anymore, `defineRule` will provide auto-complete and
typechecking for `meta` and `create`.
- Migrates all rules to typescript
  - Extra type guards are also added to make typescript happy.

All existing `eslint-config-next` unit test cases passed after the
migration.
parent cd04606d
...@@ -15,6 +15,7 @@ ...@@ -15,6 +15,7 @@
"glob": "7.1.7" "glob": "7.1.7"
}, },
"devDependencies": { "devDependencies": {
"@types/glob": "7.1.1",
"eslint": "7.24.0" "eslint": "7.24.0"
}, },
"scripts": { "scripts": {
......
const NodeAttributes = require('../utils/node-attributes.js') import { defineRule } from '../utils/define-rule'
import NodeAttributes from '../utils/node-attributes'
const url = 'https://nextjs.org/docs/messages/google-font-display' const url = 'https://nextjs.org/docs/messages/google-font-display'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Enforce font-display behavior with Google Fonts.', description: 'Enforce font-display behavior with Google Fonts.',
...@@ -12,10 +13,10 @@ module.exports = { ...@@ -12,10 +13,10 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
JSXOpeningElement(node) { JSXOpeningElement(node) {
let message let message: string | undefined
if (node.name.name !== 'link') { if (node.name.name !== 'link') {
return return
...@@ -58,4 +59,4 @@ module.exports = { ...@@ -58,4 +59,4 @@ module.exports = {
}, },
} }
}, },
} })
const NodeAttributes = require('../utils/node-attributes.js') import { defineRule } from '../utils/define-rule'
import NodeAttributes from '../utils/node-attributes'
const url = 'https://nextjs.org/docs/messages/google-font-preconnect' const url = 'https://nextjs.org/docs/messages/google-font-preconnect'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Ensure `preconnect` is used with Google Fonts.', description: 'Ensure `preconnect` is used with Google Fonts.',
...@@ -12,7 +13,7 @@ module.exports = { ...@@ -12,7 +13,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
JSXOpeningElement(node) { JSXOpeningElement(node) {
if (node.name.name !== 'link') { if (node.name.name !== 'link') {
...@@ -43,4 +44,4 @@ module.exports = { ...@@ -43,4 +44,4 @@ module.exports = {
}, },
} }
}, },
} })
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/inline-script-id' const url = 'https://nextjs.org/docs/messages/inline-script-id'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: description:
...@@ -11,7 +13,7 @@ module.exports = { ...@@ -11,7 +13,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
let nextScriptImportName = null let nextScriptImportName = null
return { return {
...@@ -70,4 +72,4 @@ module.exports = { ...@@ -70,4 +72,4 @@ module.exports = {
}, },
} }
}, },
} })
const NodeAttributes = require('../utils/node-attributes.js') import { defineRule } from '../utils/define-rule'
import NodeAttributes from '../utils/node-attributes'
const SUPPORTED_SRCS = [ const SUPPORTED_SRCS = [
'www.google-analytics.com/analytics.js', 'www.google-analytics.com/analytics.js',
...@@ -18,7 +19,7 @@ const containsStr = (str, strList) => { ...@@ -18,7 +19,7 @@ const containsStr = (str, strList) => {
return strList.some((s) => str.includes(s)) return strList.some((s) => str.includes(s))
} }
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description, description,
...@@ -28,7 +29,7 @@ module.exports = { ...@@ -28,7 +29,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
JSXOpeningElement(node) { JSXOpeningElement(node) {
if (node.name.name !== 'script') { if (node.name.name !== 'script') {
...@@ -76,4 +77,4 @@ module.exports = { ...@@ -76,4 +77,4 @@ module.exports = {
}, },
} }
}, },
} })
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-assign-module-variable' const url = 'https://nextjs.org/docs/messages/no-assign-module-variable'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent assignment to the `module` variable.', description: 'Prevent assignment to the `module` variable.',
...@@ -11,13 +12,16 @@ module.exports = { ...@@ -11,13 +12,16 @@ module.exports = {
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
VariableDeclaration(node) { VariableDeclaration(node) {
// Checks node.declarations array for variable with id.name of `module` // Checks node.declarations array for variable with id.name of `module`
const moduleVariableFound = node.declarations.some( const moduleVariableFound = node.declarations.some((declaration) => {
(declaration) => declaration.id.name === 'module' if ('name' in declaration.id) {
) return declaration.id.name === 'module'
}
return false
})
// Return early if no `module` variable is found // Return early if no `module` variable is found
if (!moduleVariableFound) { if (!moduleVariableFound) {
...@@ -31,4 +35,4 @@ module.exports = { ...@@ -31,4 +35,4 @@ module.exports = {
}, },
} }
}, },
} })
const path = require('path') import { defineRule } from '../utils/define-rule'
import * as path from 'path'
const url = const url =
'https://nextjs.org/docs/messages/no-before-interactive-script-outside-document' 'https://nextjs.org/docs/messages/no-before-interactive-script-outside-document'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: description:
...@@ -14,7 +15,7 @@ module.exports = { ...@@ -14,7 +15,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
let scriptImportName = null let scriptImportName = null
return { return {
...@@ -56,4 +57,4 @@ module.exports = { ...@@ -56,4 +57,4 @@ module.exports = {
}, },
} }
}, },
} })
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-css-tags' const url = 'https://nextjs.org/docs/messages/no-css-tags'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent manual stylesheet tags.', description: 'Prevent manual stylesheet tags.',
...@@ -10,7 +11,7 @@ module.exports = { ...@@ -10,7 +11,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
JSXOpeningElement(node) { JSXOpeningElement(node) {
if (node.name.name !== 'link') { if (node.name.name !== 'link') {
...@@ -43,4 +44,4 @@ module.exports = { ...@@ -43,4 +44,4 @@ module.exports = {
}, },
} }
}, },
} })
const path = require('path') import { defineRule } from '../utils/define-rule'
import * as path from 'path'
const url = 'https://nextjs.org/docs/messages/no-document-import-in-page' const url = 'https://nextjs.org/docs/messages/no-document-import-in-page'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: description:
...@@ -13,7 +14,7 @@ module.exports = { ...@@ -13,7 +14,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
ImportDeclaration(node) { ImportDeclaration(node) {
if (node.source.value !== 'next/document') { if (node.source.value !== 'next/document') {
...@@ -38,4 +39,4 @@ module.exports = { ...@@ -38,4 +39,4 @@ module.exports = {
}, },
} }
}, },
} })
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-duplicate-head' const url = 'https://nextjs.org/docs/messages/no-duplicate-head'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: description:
...@@ -11,7 +12,7 @@ module.exports = { ...@@ -11,7 +12,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
let documentImportName let documentImportName
return { return {
ImportDeclaration(node) { ImportDeclaration(node) {
...@@ -30,6 +31,7 @@ module.exports = { ...@@ -30,6 +31,7 @@ module.exports = {
(ancestorNode) => (ancestorNode) =>
ancestorNode.type === 'ClassDeclaration' && ancestorNode.type === 'ClassDeclaration' &&
ancestorNode.superClass && ancestorNode.superClass &&
'name' in ancestorNode.superClass &&
ancestorNode.superClass.name === documentImportName ancestorNode.superClass.name === documentImportName
) )
...@@ -37,7 +39,13 @@ module.exports = { ...@@ -37,7 +39,13 @@ module.exports = {
return return
} }
if (node.argument && node.argument.children) { // @ts-expect-error - `node.argument` could be a `JSXElement` which has property `children`
if (
node.argument &&
'children' in node.argument &&
node.argument.children
) {
// @ts-expect-error - `node.argument` could be a `JSXElement` which has property `children`
const headComponents = node.argument.children.filter( const headComponents = node.argument.children.filter(
(childrenNode) => (childrenNode) =>
childrenNode.openingElement && childrenNode.openingElement &&
...@@ -57,4 +65,4 @@ module.exports = { ...@@ -57,4 +65,4 @@ module.exports = {
}, },
} }
}, },
} })
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-head-element' const url = 'https://nextjs.org/docs/messages/no-head-element'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent usage of `<head>` element.', description: 'Prevent usage of `<head>` element.',
...@@ -11,7 +13,7 @@ module.exports = { ...@@ -11,7 +13,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
JSXOpeningElement(node) { JSXOpeningElement(node) {
const paths = context.getFilename() const paths = context.getFilename()
...@@ -29,4 +31,4 @@ module.exports = { ...@@ -29,4 +31,4 @@ module.exports = {
}, },
} }
}, },
} })
const path = require('path') import { defineRule } from '../utils/define-rule'
import * as path from 'path'
const url = 'https://nextjs.org/docs/messages/no-head-import-in-document' const url = 'https://nextjs.org/docs/messages/no-head-import-in-document'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent usage of `next/head` in `pages/_document.js`.', description: 'Prevent usage of `next/head` in `pages/_document.js`.',
...@@ -12,7 +13,7 @@ module.exports = { ...@@ -12,7 +13,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
ImportDeclaration(node) { ImportDeclaration(node) {
if (node.source.value !== 'next/head') { if (node.source.value !== 'next/head') {
...@@ -38,4 +39,4 @@ module.exports = { ...@@ -38,4 +39,4 @@ module.exports = {
}, },
} }
}, },
} })
// @ts-check import { defineRule } from '../utils/define-rule'
const path = require('path') import * as path from 'path'
const fs = require('fs') import * as fs from 'fs'
const getRootDir = require('../utils/get-root-dirs') import { getRootDirs } from '../utils/get-root-dirs'
const {
import {
getUrlFromPagesDirectories, getUrlFromPagesDirectories,
normalizeURL, normalizeURL,
execOnce, execOnce,
} = require('../utils/url') } from '../utils/url'
const pagesDirWarning = execOnce((pagesDirs) => { const pagesDirWarning = execOnce((pagesDirs) => {
console.warn( console.warn(
...@@ -21,7 +22,7 @@ const fsExistsSyncCache = {} ...@@ -21,7 +22,7 @@ const fsExistsSyncCache = {}
const url = 'https://nextjs.org/docs/messages/no-html-link-for-pages' const url = 'https://nextjs.org/docs/messages/no-html-link-for-pages'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: description:
...@@ -51,16 +52,12 @@ module.exports = { ...@@ -51,16 +52,12 @@ module.exports = {
/** /**
* Creates an ESLint rule listener. * Creates an ESLint rule listener.
*
* @param {import('eslint').Rule.RuleContext} context - ESLint rule context
* @returns {import('eslint').Rule.RuleListener} An ESLint rule listener
*/ */
create: function (context) { create(context) {
/** @type {(string|string[])[]} */ const ruleOptions: (string | string[])[] = context.options
const ruleOptions = context.options
const [customPagesDirectory] = ruleOptions const [customPagesDirectory] = ruleOptions
const rootDirs = getRootDir(context) const rootDirs = getRootDirs(context)
const pagesDirs = ( const pagesDirs = (
customPagesDirectory customPagesDirectory
...@@ -135,4 +132,4 @@ module.exports = { ...@@ -135,4 +132,4 @@ module.exports = {
}, },
} }
}, },
} })
import type { Rule } from 'eslint' import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-img-element' const url = 'https://nextjs.org/docs/messages/no-img-element'
export const meta: Rule.RuleMetaData = { export = defineRule({
docs: { meta: {
description: 'Prevent usage of `<img>` element to prevent layout shift.', docs: {
category: 'HTML', description: 'Prevent usage of `<img>` element to prevent layout shift.',
recommended: true, category: 'HTML',
url, recommended: true,
url,
},
type: 'problem',
schema: [],
}, },
type: 'problem', create(context) {
schema: [], return {
} JSXOpeningElement(node) {
if (node.name.name !== 'img') {
export const create: Rule.RuleModule['create'] = (context) => { return
return { }
JSXOpeningElement(node) {
if (node.name.name !== 'img') {
return
}
if (node.attributes.length === 0) { if (node.attributes.length === 0) {
return return
} }
if (node.parent?.parent?.openingElement?.name?.name === 'picture') { if (node.parent?.parent?.openingElement?.name?.name === 'picture') {
return return
} }
context.report({ context.report({
node, node,
message: `Do not use \`<img>\` element. Use \`<Image />\` from \`next/image\` instead. See: ${url}`, message: `Do not use \`<img>\` element. Use \`<Image />\` from \`next/image\` instead. See: ${url}`,
}) })
}, },
} }
} },
})
const NodeAttributes = require('../utils/node-attributes.js') import { defineRule } from '../utils/define-rule'
const { sep, posix } = require('path') import NodeAttributes from '../utils/node-attributes'
import { sep, posix } from 'path'
import type { AST } from 'eslint'
const url = 'https://nextjs.org/docs/messages/no-page-custom-font' const url = 'https://nextjs.org/docs/messages/no-page-custom-font'
module.exports = { function isIdentifierMatch(id1, id2) {
return (id1 === null && id2 === null) || (id1 && id2 && id1.name === id2.name)
}
export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent page-only custom fonts.', description: 'Prevent page-only custom fonts.',
...@@ -13,7 +19,7 @@ module.exports = { ...@@ -13,7 +19,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
const paths = context.getFilename().split('pages') const paths = context.getFilename().split('pages')
const page = paths[paths.length - 1] const page = paths[paths.length - 1]
...@@ -53,6 +59,7 @@ module.exports = { ...@@ -53,6 +59,7 @@ module.exports = {
if ( if (
node.declaration.type === 'ClassDeclaration' && node.declaration.type === 'ClassDeclaration' &&
node.declaration.superClass && node.declaration.superClass &&
'name' in node.declaration.superClass &&
node.declaration.superClass.name === documentImportName node.declaration.superClass.name === documentImportName
) { ) {
localDefaultExportId = node.declaration.id localDefaultExportId = node.declaration.id
...@@ -73,7 +80,7 @@ module.exports = { ...@@ -73,7 +80,7 @@ module.exports = {
// find the top level of the module // find the top level of the module
const program = ancestors.find( const program = ancestors.find(
(ancestor) => ancestor.type === 'Program' (ancestor) => ancestor.type === 'Program'
) ) as AST.Program
// go over each token to find the combination of `export default <name>` // go over each token to find the combination of `export default <name>`
for (let i = 0; i <= program.tokens.length - 1; i++) { for (let i = 0; i <= program.tokens.length - 1; i++) {
...@@ -106,22 +113,28 @@ module.exports = { ...@@ -106,22 +113,28 @@ module.exports = {
if (exportDeclarationType === 'ClassDeclaration') { if (exportDeclarationType === 'ClassDeclaration') {
return ( return (
ancestor.type === exportDeclarationType && ancestor.type === exportDeclarationType &&
'superClass' in ancestor &&
ancestor.superClass && ancestor.superClass &&
'name' in ancestor.superClass &&
ancestor.superClass.name === documentImportName ancestor.superClass.name === documentImportName
) )
} }
// export default function ... if ('id' in ancestor) {
if (exportDeclarationType === 'FunctionDeclaration') { // export default function ...
return ( if (exportDeclarationType === 'FunctionDeclaration') {
ancestor.type === exportDeclarationType && return (
isIdentifierMatch(ancestor.id, localDefaultExportId) ancestor.type === exportDeclarationType &&
) isIdentifierMatch(ancestor.id, localDefaultExportId)
)
}
// function ...() {} export default ...
// class ... extends ...; export default ...
return isIdentifierMatch(ancestor.id, localDefaultExportId)
} }
// function ...() {} export default ... return false
// class ... extends ...; export default ...
return isIdentifierMatch(ancestor.id, localDefaultExportId)
}) })
// file starts with _document and this <link /> is within the default export // file starts with _document and this <link /> is within the default export
...@@ -154,8 +167,4 @@ module.exports = { ...@@ -154,8 +167,4 @@ module.exports = {
}, },
} }
}, },
} })
function isIdentifierMatch(id1, id2) {
return (id1 === null && id2 === null) || (id1 && id2 && id1.name === id2.name)
}
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-script-component-in-head' const url = 'https://nextjs.org/docs/messages/no-script-component-in-head'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent usage of `next/script` in `next/head` component.', description: 'Prevent usage of `next/script` in `next/head` component.',
...@@ -10,7 +11,7 @@ module.exports = { ...@@ -10,7 +11,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
let isNextHead = null let isNextHead = null
return { return {
...@@ -52,4 +53,4 @@ module.exports = { ...@@ -52,4 +53,4 @@ module.exports = {
}, },
} }
}, },
} })
const path = require('path') import { defineRule } from '../utils/define-rule'
import * as path from 'path'
const url = 'https://nextjs.org/docs/messages/no-styled-jsx-in-document' const url = 'https://nextjs.org/docs/messages/no-styled-jsx-in-document'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent usage of `styled-jsx` in `pages/_document.js`.', description: 'Prevent usage of `styled-jsx` in `pages/_document.js`.',
...@@ -12,7 +13,7 @@ module.exports = { ...@@ -12,7 +13,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
JSXOpeningElement(node) { JSXOpeningElement(node) {
const document = context.getFilename().split('pages')[1] const document = context.getFilename().split('pages')[1]
...@@ -44,4 +45,4 @@ module.exports = { ...@@ -44,4 +45,4 @@ module.exports = {
}, },
} }
}, },
} })
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-sync-scripts' const url = 'https://nextjs.org/docs/messages/no-sync-scripts'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent synchronous scripts.', description: 'Prevent synchronous scripts.',
...@@ -10,7 +12,7 @@ module.exports = { ...@@ -10,7 +12,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
return { return {
JSXOpeningElement(node) { JSXOpeningElement(node) {
if (node.name.name !== 'script') { if (node.name.name !== 'script') {
...@@ -35,4 +37,4 @@ module.exports = { ...@@ -35,4 +37,4 @@ module.exports = {
}, },
} }
}, },
} })
import { defineRule } from '../utils/define-rule'
const url = 'https://nextjs.org/docs/messages/no-title-in-document-head' const url = 'https://nextjs.org/docs/messages/no-title-in-document-head'
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: description:
...@@ -11,7 +12,7 @@ module.exports = { ...@@ -11,7 +12,7 @@ module.exports = {
type: 'problem', type: 'problem',
schema: [], schema: [],
}, },
create: function (context) { create(context) {
let headFromNextDocument = false let headFromNextDocument = false
return { return {
ImportDeclaration(node) { ImportDeclaration(node) {
...@@ -51,4 +52,4 @@ module.exports = { ...@@ -51,4 +52,4 @@ module.exports = {
}, },
} }
}, },
} })
const path = require('path') import { defineRule } from '../utils/define-rule'
import * as path from 'path'
const NEXT_EXPORT_FUNCTIONS = [ const NEXT_EXPORT_FUNCTIONS = [
'getStaticProps', 'getStaticProps',
...@@ -40,7 +41,7 @@ function minDistance(a, b) { ...@@ -40,7 +41,7 @@ function minDistance(a, b) {
} }
/* eslint-disable eslint-plugin/require-meta-docs-url */ /* eslint-disable eslint-plugin/require-meta-docs-url */
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent common typos in Next.js data fetching functions.', description: 'Prevent common typos in Next.js data fetching functions.',
...@@ -50,7 +51,7 @@ module.exports = { ...@@ -50,7 +51,7 @@ module.exports = {
schema: [], schema: [],
}, },
create: function (context) { create(context) {
function checkTypos(node, name) { function checkTypos(node, name) {
if (NEXT_EXPORT_FUNCTIONS.includes(name)) { if (NEXT_EXPORT_FUNCTIONS.includes(name)) {
return return
...@@ -105,4 +106,4 @@ module.exports = { ...@@ -105,4 +106,4 @@ module.exports = {
}, },
} }
}, },
} })
import { defineRule } from '../utils/define-rule'
// Keep in sync with next.js polyfills file : https://github.com/vercel/next.js/blob/master/packages/next-polyfill-nomodule/src/index.js // Keep in sync with next.js polyfills file : https://github.com/vercel/next.js/blob/master/packages/next-polyfill-nomodule/src/index.js
const NEXT_POLYFILLED_FEATURES = [ const NEXT_POLYFILLED_FEATURES = [
'Array.prototype.@@iterator', 'Array.prototype.@@iterator',
...@@ -69,7 +71,7 @@ const url = 'https://nextjs.org/docs/messages/no-unwanted-polyfillio' ...@@ -69,7 +71,7 @@ const url = 'https://nextjs.org/docs/messages/no-unwanted-polyfillio'
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
// Rule Definition // Rule Definition
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
module.exports = { export = defineRule({
meta: { meta: {
docs: { docs: {
description: 'Prevent duplicate polyfills from Polyfill.io.', description: 'Prevent duplicate polyfills from Polyfill.io.',
...@@ -81,7 +83,7 @@ module.exports = { ...@@ -81,7 +83,7 @@ module.exports = {
schema: [], schema: [],
}, },
create: function (context) { create(context) {
let scriptImport = null let scriptImport = null
return { return {
...@@ -132,4 +134,4 @@ module.exports = { ...@@ -132,4 +134,4 @@ module.exports = {
}, },
} }
}, },
} })
import type { Rule } from 'eslint'
export const defineRule = (rule: Rule.RuleModule) => rule
// @ts-check import * as glob from 'glob'
const glob = require('glob') import type { Rule } from 'eslint'
/** /**
* Process a Next.js root directory glob. * Process a Next.js root directory glob.
*
* @param {string} rootDir - A Next.js root directory glob.
* @returns {string[]} - An array of Root directories.
*/ */
const processRootDir = (rootDir) => { const processRootDir = (rootDir: string): string[] => {
// Ensures we only match folders. // Ensures we only match folders.
if (!rootDir.endsWith('/')) rootDir += '/' if (!rootDir.endsWith('/')) rootDir += '/'
return glob.sync(rootDir) return glob.sync(rootDir)
} }
/** /**
* Gets one or more Root * Gets one or more Root, returns an array of root directories.
*
* @param {import('eslint').Rule.RuleContext} context - ESLint rule context
* @returns An array of root directories.
*/ */
const getRootDirs = (context) => { export const getRootDirs = (context: Rule.RuleContext) => {
let rootDirs = [context.getCwd()] let rootDirs = [context.getCwd()]
/** @type {{rootDir?:string|string[]}|undefined} */ const nextSettings: { rootDir?: string | string[] } =
const nextSettings = context.settings.next || {} context.settings.next || {}
let rootDir = nextSettings.rootDir let rootDir = nextSettings.rootDir
if (typeof rootDir === 'string') { if (typeof rootDir === 'string') {
...@@ -36,5 +30,3 @@ const getRootDirs = (context) => { ...@@ -36,5 +30,3 @@ const getRootDirs = (context) => {
return rootDirs return rootDirs
} }
module.exports = getRootDirs
...@@ -11,24 +11,40 @@ ...@@ -11,24 +11,40 @@
Inclusion of hasValue is in case an eslint rule cares about boolean values Inclusion of hasValue is in case an eslint rule cares about boolean values
explicitly assigned to attribute vs the attribute being used as a flag explicitly assigned to attribute vs the attribute being used as a flag
*/ */
class NodeAttributes { export default class NodeAttributes {
attributes: Record<
string,
| {
hasValue?: false
}
| {
hasValue: true
value: any
}
>
constructor(ASTnode) { constructor(ASTnode) {
this.attributes = {} this.attributes = {}
ASTnode.attributes.forEach((attribute) => { ASTnode.attributes.forEach((attribute) => {
if (!attribute.type || attribute.type !== 'JSXAttribute') { if (!attribute.type || attribute.type !== 'JSXAttribute') {
return return
} }
this.attributes[attribute.name.name] = {
hasValue: !!attribute.value, if (!!attribute.value) {
} // hasValue
if (attribute.value) { const value = attribute.value.value
if (attribute.value.value) { ? attribute.value.value
this.attributes[attribute.name.name].value = attribute.value.value : typeof attribute.value.expression.value !== 'undefined'
} else if (attribute.value.expression) { ? attribute.value.expression.value
this.attributes[attribute.name.name].value = : attribute.value.expression.properties
typeof attribute.value.expression.value !== 'undefined'
? attribute.value.expression.value this.attributes[attribute.name.name] = {
: attribute.value.expression.properties hasValue: true,
value,
}
} else {
this.attributes[attribute.name.name] = {
hasValue: false,
} }
} }
}) })
...@@ -36,19 +52,23 @@ class NodeAttributes { ...@@ -36,19 +52,23 @@ class NodeAttributes {
hasAny() { hasAny() {
return !!Object.keys(this.attributes).length return !!Object.keys(this.attributes).length
} }
has(attrName) { has(attrName: string) {
return !!this.attributes[attrName] return !!this.attributes[attrName]
} }
hasValue(attrName) { hasValue(attrName: string) {
return !!this.attributes[attrName].hasValue return !!this.attributes[attrName].hasValue
} }
value(attrName) { value(attrName: string) {
if (!this.attributes[attrName]) { const attr = this.attributes[attrName]
if (!attr) {
return true return true
} }
return this.attributes[attrName].value if (attr.hasValue) {
return attr.value
}
return undefined
} }
} }
module.exports = NodeAttributes
const fs = require('fs') import * as path from 'path'
const path = require('path') import * as fs from 'fs'
// Cache for fs.lstatSync lookup. // Cache for fs.lstatSync lookup.
// Prevent multiple blocking IO requests that have already been calculated. // Prevent multiple blocking IO requests that have already been calculated.
...@@ -11,53 +11,26 @@ const fsLstatSync = (source) => { ...@@ -11,53 +11,26 @@ const fsLstatSync = (source) => {
/** /**
* Checks if the source is a directory. * Checks if the source is a directory.
* @param {string} source
*/ */
function isDirectory(source) { function isDirectory(source: string) {
return fsLstatSync(source).isDirectory() return fsLstatSync(source).isDirectory()
} }
/** /**
* Checks if the source is a directory. * Checks if the source is a directory.
* @param {string} source
*/ */
function isSymlink(source) { function isSymlink(source: string) {
return fsLstatSync(source).isSymbolicLink() return fsLstatSync(source).isSymbolicLink()
} }
/**
* Gets the possible URLs from a directory.
* @param {string} urlprefix
* @param {string[]} directories
*/
function getUrlFromPagesDirectories(urlPrefix, directories) {
return Array.from(
// De-duplicate similar pages across multiple directories.
new Set(
directories
.map((directory) => parseUrlForPages(urlPrefix, directory))
.flat()
.map(
// Since the URLs are normalized we add `^` and `$` to the RegExp to make sure they match exactly.
(url) => `^${normalizeURL(url)}$`
)
)
).map((urlReg) => {
urlReg = urlReg.replace(/\[.*\]/g, '((?!.+?\\..+?).*?)')
return new RegExp(urlReg)
})
}
// Cache for fs.readdirSync lookup. // Cache for fs.readdirSync lookup.
// Prevent multiple blocking IO requests that have already been calculated. // Prevent multiple blocking IO requests that have already been calculated.
const fsReadDirSyncCache = {} const fsReadDirSyncCache = {}
/** /**
* Recursively parse directory for page URLs. * Recursively parse directory for page URLs.
* @param {string} urlprefix
* @param {string} directory
*/ */
function parseUrlForPages(urlprefix, directory) { function parseUrlForPages(urlprefix: string, directory: string) {
fsReadDirSyncCache[directory] = fsReadDirSyncCache[directory] =
fsReadDirSyncCache[directory] || fs.readdirSync(directory) fsReadDirSyncCache[directory] || fs.readdirSync(directory)
const res = [] const res = []
...@@ -84,9 +57,8 @@ function parseUrlForPages(urlprefix, directory) { ...@@ -84,9 +57,8 @@ function parseUrlForPages(urlprefix, directory) {
* - Replaces `index.html` with `/` * - Replaces `index.html` with `/`
* - Makes sure all URLs are have a trailing `/` * - Makes sure all URLs are have a trailing `/`
* - Removes query string * - Removes query string
* @param {string} url
*/ */
function normalizeURL(url) { export function normalizeURL(url: string) {
if (!url) { if (!url) {
return return
} }
...@@ -101,11 +73,37 @@ function normalizeURL(url) { ...@@ -101,11 +73,37 @@ function normalizeURL(url) {
return url return url
} }
function execOnce(fn) { /**
* Gets the possible URLs from a directory.
*/
export function getUrlFromPagesDirectories(
urlPrefix: string,
directories: string[]
) {
return Array.from(
// De-duplicate similar pages across multiple directories.
new Set(
directories
.map((directory) => parseUrlForPages(urlPrefix, directory))
.flat()
.map(
// Since the URLs are normalized we add `^` and `$` to the RegExp to make sure they match exactly.
(url) => `^${normalizeURL(url)}$`
)
)
).map((urlReg) => {
urlReg = urlReg.replace(/\[.*\]/g, '((?!.+?\\..+?).*?)')
return new RegExp(urlReg)
})
}
export function execOnce<TArgs extends any[], TResult extends unknown>(
fn: (...args: TArgs) => TResult
): (...args: TArgs) => TResult {
let used = false let used = false
let result let result: TResult
return (...args) => { return (...args: TArgs) => {
if (!used) { if (!used) {
used = true used = true
result = fn(...args) result = fn(...args)
...@@ -113,9 +111,3 @@ function execOnce(fn) { ...@@ -113,9 +111,3 @@ function execOnce(fn) {
return result return result
} }
} }
module.exports = {
getUrlFromPagesDirectories,
normalizeURL,
execOnce,
}
...@@ -419,11 +419,13 @@ importers: ...@@ -419,11 +419,13 @@ importers:
packages/eslint-plugin-next: packages/eslint-plugin-next:
specifiers: specifiers:
'@types/glob': 7.1.1
eslint: 7.24.0 eslint: 7.24.0
glob: 7.1.7 glob: 7.1.7
dependencies: dependencies:
glob: 7.1.7 glob: 7.1.7
devDependencies: devDependencies:
'@types/glob': 7.1.1
eslint: 7.24.0 eslint: 7.24.0
packages/font: packages/font:
...@@ -594,8 +596,8 @@ importers: ...@@ -594,8 +596,8 @@ importers:
source-map: 0.6.1 source-map: 0.6.1
stream-browserify: 3.0.0 stream-browserify: 3.0.0
stream-http: 3.1.1 stream-http: 3.1.1
string_decoder: 1.3.0
string-hash: 1.1.3 string-hash: 1.1.3
string_decoder: 1.3.0
strip-ansi: 6.0.0 strip-ansi: 6.0.0
styled-jsx: 5.0.7 styled-jsx: 5.0.7
tar: 6.1.11 tar: 6.1.11
...@@ -784,8 +786,8 @@ importers: ...@@ -784,8 +786,8 @@ importers:
source-map: 0.6.1 source-map: 0.6.1
stream-browserify: 3.0.0 stream-browserify: 3.0.0
stream-http: 3.1.1 stream-http: 3.1.1
string_decoder: 1.3.0
string-hash: 1.1.3 string-hash: 1.1.3
string_decoder: 1.3.0
strip-ansi: 6.0.0 strip-ansi: 6.0.0
tar: 6.1.11 tar: 6.1.11
taskr: 1.1.0 taskr: 1.1.0
...@@ -11618,8 +11620,8 @@ packages: ...@@ -11618,8 +11620,8 @@ packages:
engines: { node: '>=10' } engines: { node: '>=10' }
hasBin: true hasBin: true
dependencies: dependencies:
is-text-path: 1.0.1
JSONStream: 1.3.5 JSONStream: 1.3.5
is-text-path: 1.0.1
lodash: 4.17.21 lodash: 4.17.21
meow: 8.1.2 meow: 8.1.2
split2: 2.2.0 split2: 2.2.0
......
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