Skip to content

feat: add support for ignoring sync methods from certain locations #424

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
57 changes: 57 additions & 0 deletions docs/rules/no-sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ fs.readFileSync(somePath).toString();
#### ignores

You can `ignore` specific function names using this option.
Additionally, if you are using TypeScript you can optionally specify where the function is declared.

Examples of **incorrect** code for this rule with the `{ ignores: ['readFileSync'] }` option:

Expand All @@ -78,6 +79,62 @@ Examples of **correct** code for this rule with the `{ ignores: ['readFileSync']
fs.readFileSync(somePath);
```

##### Advanced (TypeScript only)

You can provide a list of specifiers to ignore. Specifiers are typed as follows:

```ts
type Specifier =
| string
| {
from: "file";
path?: string;
name?: string[];
}
| {
from: "package";
package?: string;
name?: string[];
}
| {
from: "lib";
name?: string[];
}
```

###### From a file

Examples of **correct** code for this rule with the ignore file specifier:

```js
/*eslint n/no-sync: ["error", { ignores: [{ from: 'file', path: './foo.ts' }]}] */

import { fooSync } from "./foo"
fooSync()
```

###### From a package

Examples of **correct** code for this rule with the ignore package specifier:

```js
/*eslint n/no-sync: ["error", { ignores: [{ from: 'package', package: 'effect' }]}] */

import { Effect } from "effect"
const value = Effect.runSync(Effect.succeed(42))
```

###### From the TypeScript library

Examples of **correct** code for this rule with the ignore lib specifier:

```js
/*eslint n/no-sync: ["error", { ignores: [{ from: 'lib' }]}] */

const stylesheet = new CSSStyleSheet()
stylesheet.replaceSync("body { font-size: 1.4em; } p { color: red; }")
```

## 🔎 Implementation

- [Rule source](../../lib/rules/no-sync.js)
Expand Down
123 changes: 119 additions & 4 deletions lib/rules/no-sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,22 @@
*/
"use strict"

let typeMatchesSpecifier =
/** @type {import('ts-declaration-location').default | undefined} */
(undefined)

try {
typeMatchesSpecifier =
/** @type {import('ts-declaration-location').default} */ (
/** @type {unknown} */ (require("ts-declaration-location"))
)

// eslint-disable-next-line no-empty -- Deliberately left empty.
} catch {}
const getTypeOfNode = require("../util/get-type-of-node")
const getParserServices = require("../util/get-parser-services")
const getFullTypeName = require("../util/get-full-type-name")

const selectors = [
// fs.readFileSync()
// readFileSync.call(null, 'path')
Expand Down Expand Up @@ -32,7 +48,56 @@ module.exports = {
},
ignores: {
type: "array",
items: { type: "string" },
items: {
oneOf: [
{ type: "string" },
{
type: "object",
properties: {
from: { const: "file" },
path: {
type: "string",
},
name: {
type: "array",
items: {
type: "string",
},
},
},
additionalProperties: false,
},
{
type: "object",
properties: {
from: { const: "lib" },
name: {
type: "array",
items: {
type: "string",
},
},
},
additionalProperties: false,
},
{
type: "object",
properties: {
from: { const: "package" },
package: {
type: "string",
},
name: {
type: "array",
items: {
type: "string",
},
},
},
additionalProperties: false,
},
],
},
default: [],
},
},
Expand All @@ -57,15 +122,65 @@ module.exports = {
* @returns {void}
*/
[selector.join(",")](node) {
if (ignores.includes(node.name)) {
return
const parserServices = getParserServices(context)

/**
* @type {import('typescript').Type | undefined | null}
*/
let type = undefined

/**
* @type {string | undefined | null}
*/
let fullName = undefined

for (const ignore of ignores) {
if (typeof ignore === "string") {
if (ignore === node.name) {
return
}

continue
}

if (
parserServices === null ||
parserServices.program === null ||
typeMatchesSpecifier === undefined
) {
throw new Error(
'TypeScript parser services not available. Rule "n/no-sync" is configured to use "ignores" option with a non-string value. This requires TypeScript parser services to be available.'
)
}

type =
type === undefined
? getTypeOfNode(node, parserServices)
: type

fullName =
fullName === undefined
? getFullTypeName(type)
: fullName

if (
typeMatchesSpecifier(
parserServices.program,
ignore,
type
) &&
(ignore.name === undefined ||
ignore.name.includes(fullName ?? node.name))
) {
return
}
}

context.report({
node: node.parent,
messageId: "noSync",
data: {
propertyName: node.name,
propertyName: fullName ?? node.name,
},
})
},
Expand Down
47 changes: 47 additions & 0 deletions lib/util/get-full-type-name.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"use strict"

const ts = (() => {
try {
// eslint-disable-next-line n/no-unpublished-require
return require("typescript")
} catch {
return null
}
})()

/**
* @param {import('typescript').Type | null} type
* @returns {string | null}
*/
module.exports = function getFullTypeName(type) {
if (ts === null || type === null) {
return null
}

/**
* @type {string[]}
*/
let nameParts = []
let currentSymbol = type.getSymbol()
while (currentSymbol !== undefined) {
if (
currentSymbol.valueDeclaration?.kind === ts.SyntaxKind.SourceFile ||
currentSymbol.valueDeclaration?.kind ===
ts.SyntaxKind.ModuleDeclaration
) {
break
}

nameParts.unshift(currentSymbol.getName())
currentSymbol =
/** @type {import('typescript').Symbol & {parent: import('typescript').Symbol | undefined}} */ (
currentSymbol
).parent
}

if (nameParts.length === 0) {
return null
}

return nameParts.join(".")
}
24 changes: 24 additions & 0 deletions lib/util/get-parser-services.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"use strict"

const {
getParserServices: getParserServicesFromTsEslint,
} = require("@typescript-eslint/utils/eslint-utils")

/**
* Get the TypeScript parser services.
* If TypeScript isn't present, returns `null`.
*
* @param {import('eslint').Rule.RuleContext} context - rule context
* @returns {import('@typescript-eslint/parser').ParserServices | null}
*/
module.exports = function getParserServices(context) {
// Not using tseslint parser?
if (
context.sourceCode.parserServices?.esTreeNodeToTSNodeMap == null ||
context.sourceCode.parserServices.tsNodeToESTreeNodeMap == null
) {
return null
}

return getParserServicesFromTsEslint(/** @type {any} */ (context), true)
}
21 changes: 21 additions & 0 deletions lib/util/get-type-of-node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"use strict"

/**
* Get the type of a node.
* If TypeScript isn't present, returns `null`.
*
* @param {import('estree').Node} node - A node
* @param {import('@typescript-eslint/parser').ParserServices} parserServices - A parserServices
* @returns {import('typescript').Type | null}
*/
module.exports = function getTypeOfNode(node, parserServices) {
const { esTreeNodeToTSNodeMap, program } = parserServices
if (program === null) {
return null
}
const tsNode = esTreeNodeToTSNodeMap.get(/** @type {any} */ (node))
const checker = program.getTypeChecker()
const nodeType = checker.getTypeAtLocation(tsNode)
const constrained = checker.getBaseConstraintOfType(nodeType)
return constrained ?? nodeType
}
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,23 @@
},
"dependencies": {
"@eslint-community/eslint-utils": "^4.4.1",
"@typescript-eslint/utils": "^8.26.1",
"enhanced-resolve": "^5.17.1",
"eslint-plugin-es-x": "^7.8.0",
"get-tsconfig": "^4.8.1",
"globals": "^15.11.0",
"ignore": "^5.3.2",
"minimatch": "^9.0.5",
"semver": "^7.6.3"
"semver": "^7.6.3",
"ts-declaration-location": "^1.0.6"
},
"devDependencies": {
"@eslint/js": "^9.14.0",
"@types/eslint": "^9.6.1",
"@types/estree": "^1.0.6",
"@types/node": "^20.17.5",
"@typescript-eslint/parser": "^8.12.2",
"@typescript-eslint/typescript-estree": "^8.12.2",
"@typescript-eslint/parser": "^8.26.1",
"@typescript-eslint/typescript-estree": "^8.26.1",
"eslint": "^9.14.0",
"eslint-config-prettier": "^9.1.0",
"eslint-doc-generator": "^1.7.1",
Expand Down
1 change: 1 addition & 0 deletions tests/fixtures/no-sync/base/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// File needs to exists
10 changes: 10 additions & 0 deletions tests/fixtures/no-sync/base/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true
},
"include": ["**/*"]
}
1 change: 1 addition & 0 deletions tests/fixtures/no-sync/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// File needs to exists
1 change: 1 addition & 0 deletions tests/fixtures/no-sync/ignore-package/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
// File needs to exists

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Empty file.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions tests/fixtures/no-sync/ignore-package/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "test",
"version": "0.0.0",
"dependencies": {
"aaa": "0.0.0"
}
}
10 changes: 10 additions & 0 deletions tests/fixtures/no-sync/ignore-package/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true
},
"include": ["**/*"]
}
10 changes: 10 additions & 0 deletions tests/fixtures/no-sync/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"skipLibCheck": true
},
"include": ["**/*"]
}
Loading