Skip to content
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
38 changes: 38 additions & 0 deletions packages/plugin-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,44 @@ The five opt-in rules require both a configured model and an agent adapter capab

`js/no-config-file-tests` is not repository-aware and needs no agent adapter: it judges the test file it is handed, so a configured model is enough.

## Workspace-wide review

`js/no-mixed-libraries` reports the imports of a library when the workspace also uses another library for the same job, for example `zod` and `valibot`. It is registered but not enabled by `recommended`.

1. It reads the external package imports of every JavaScript, TypeScript, and Vue file in the workspace. Packages that a workspace `package.json` names, type packages, and built-in modules are left out.
2. It sends the package names, their file counts, and the directories that import them most to the model, one time for each run. The model groups the packages that do the same job.
3. It drops a group that names a package that no file imports, and a group that an `allow` set covers.
4. It reports each import of a replaced package, only in the files that the run lints.

It needs a configured model, but no agent adapter. Its verdict depends on every file in the workspace, so the core cache is off for it.

| Option | Default | Description |
| --- | --- | --- |
| `preferred` | `[]` | Packages that the repository has chosen. A preferred package becomes the canonical member of its group. |
| `allow` | `[]` | Sets of packages that can coexist, for example `[['hono', 'h3']]`. |

```ts
export default defineConfig([
{
files: ['**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts,vue}'],
plugins: { js: jsPlugin },
rules: {
'js/no-mixed-libraries': [
'warn',
{
allow: [
['hono', 'h3']
],
preferred: ['valibot']
}
],
},
},
])
```

Use it to find the libraries that a migration can remove, or to review a change that adds an import. Do not use it to ban a known library: ESLint `no-restricted-imports` does that without a model.

## How to use

Use the default export with the `js` plugin name because the bundled preset refers to `js/*` rule IDs.
Expand Down
6 changes: 6 additions & 0 deletions packages/plugin-js/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'
import plugin, {
configFileTestsRule,
duplicatedKnowledgeRule,
mixedLibrariesRule,
overlappingEntrypointsRule,
redundantCatchRule,
singleUseMaterializationRule,
Expand Down Expand Up @@ -54,4 +55,9 @@ describe('@alint-js/plugin-js registry', () => {

expect(plugin.rules?.['no-config-file-tests']).toBe(configFileTestsRule)
})

it('registers no-mixed-libraries without enabling it in recommended', () => {
expect(plugin.rules?.['no-mixed-libraries']).toBe(mixedLibrariesRule)
expect(RECOMMENDED_RULES).not.toHaveProperty('js/no-mixed-libraries')
})
})
3 changes: 3 additions & 0 deletions packages/plugin-js/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { inlineMiniatureNormalizerRule } from './rules/inline-miniature-normaliz
import { configFileTestsRule } from './rules/no-config-file-tests'
import { duplicatedKnowledgeRule } from './rules/no-duplicated-knowledge'
import { mixedLayersWithoutAbstractionRule } from './rules/no-mixed-layers-without-abstraction'
import { mixedLibrariesRule } from './rules/no-mixed-libraries'
import { overlappingEntrypointsRule } from './rules/no-overlapping-entrypoints'
import { privateSchemaToolkitRule } from './rules/no-private-schema-toolkit'
import { redundantBindingRule } from './rules/no-redundant-binding'
Expand All @@ -19,6 +20,7 @@ export { inlineMiniatureNormalizerRule } from './rules/inline-miniature-normaliz
export { configFileTestsRule } from './rules/no-config-file-tests'
export { duplicatedKnowledgeRule } from './rules/no-duplicated-knowledge'
export { mixedLayersWithoutAbstractionRule } from './rules/no-mixed-layers-without-abstraction'
export { mixedLibrariesRule } from './rules/no-mixed-libraries'
export { overlappingEntrypointsRule } from './rules/no-overlapping-entrypoints'
export { privateSchemaToolkitRule } from './rules/no-private-schema-toolkit'
export { redundantBindingRule } from './rules/no-redundant-binding'
Expand Down Expand Up @@ -51,6 +53,7 @@ export default definePlugin({
'no-config-file-tests': configFileTestsRule,
'no-duplicated-knowledge': duplicatedKnowledgeRule,
'no-mixed-layers-without-abstraction': mixedLayersWithoutAbstractionRule,
'no-mixed-libraries': mixedLibrariesRule,
'no-overlapping-entrypoints': overlappingEntrypointsRule,
'no-private-schema-toolkit': privateSchemaToolkitRule,
'no-redundant-binding': redundantBindingRule,
Expand Down
46 changes: 46 additions & 0 deletions packages/plugin-js/src/rules/no-mixed-libraries/imports.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest'

import { extractPackageImports, packageNameFrom } from './imports'

describe('packageNameFrom', () => {
it('keeps the scope and drops the subpath', () => {
expect(packageNameFrom('@scope/package/subpath')).toBe('@scope/package')
expect(packageNameFrom('es-toolkit/compat')).toBe('es-toolkit')
expect(packageNameFrom('decimal.js')).toBe('decimal.js')
})

it('returns undefined for a specifier that names no external package', () => {
for (const specifier of [
'./local',
'../up',
'~/alias',
'@/alias',
'#internal',
'node:fs',
'fs',
'virtual:uno.css',
])
expect(packageNameFrom(specifier)).toBeUndefined()
})
})

describe('extractPackageImports', () => {
it('reads static, side-effect, dynamic, and require imports with their lines', () => {
const text = [
'import { z } from \'zod\'',
'import \'uno.css\'',
'import { local } from \'./local\'',
'export * from "valibot"',
'const forage = await import(\'localforage\')',
'const ws = require(\'ws\')',
].join('\n')

expect(extractPackageImports(text)).toEqual([
{ line: 1, name: 'zod' },
{ line: 2, name: 'uno.css' },
{ line: 4, name: 'valibot' },
{ line: 5, name: 'localforage' },
{ line: 6, name: 'ws' },
])
})
})
57 changes: 57 additions & 0 deletions packages/plugin-js/src/rules/no-mixed-libraries/imports.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { isBuiltin } from 'node:module'

export interface PackageImport {
/** One-based line of the import specifier. */
line: number
/** The package that owns the specifier, for example `@scope/name` for `@scope/name/sub`. */
name: string
}

/*
* A text scan rather than a parse: the rule needs only package names and lines, from every
* JavaScript, TypeScript, and Vue file in the workspace, and a parser per language would cost
* more than the whole review. It reads static imports, re-exports, side-effect imports, dynamic
* imports, and `require` calls.
*/
const IMPORT_SPECIFIER = /\b(?:from|import|require)\s*(?:\(\s*)?(['"])([^'"\n]+)\1/g

/** Lists each external package that the source text imports, with the line of the import. */
export function extractPackageImports(text: string): PackageImport[] {
const imports: PackageImport[] = []
let line = 1
let scanned = 0

for (const match of text.matchAll(IMPORT_SPECIFIER)) {
const name = packageNameFrom(match[2])
if (name == null)
continue

for (; scanned < match.index; scanned++) {
if (text[scanned] === '\n')
line++
}
imports.push({ line, name })
}

return imports
}

/**
* Normalizes an import specifier to the name of the external package that owns it.
*
* @example
* packageNameFrom('@scope/package/subpath')
* // => '@scope/package'
* packageNameFrom('./local')
* // => undefined
*/
export function packageNameFrom(specifier: string): string | undefined {
// Relative paths, path aliases, and scheme imports such as `node:` or `virtual:` name no package.
if (!/^(?:@[\w.-]+\/)?[a-z][\w.-]*(?:\/|$)/i.test(specifier) || isBuiltin(specifier))
return undefined

const segments = specifier.split('/')
return specifier.startsWith('@')
? segments.slice(0, 2).join('/')
: segments[0]
}
2 changes: 2 additions & 0 deletions packages/plugin-js/src/rules/no-mixed-libraries/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { mixedLibrariesPrompt } from './prompt'
export { mixedLibrariesRule } from './rule'
23 changes: 23 additions & 0 deletions packages/plugin-js/src/rules/no-mixed-libraries/prompt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export const mixedLibrariesPrompt = `
You review which external packages a repository imports.
Find groups of packages that solve the same problem, where the repository can standardize on one of them.

Report a group only when every member is a general-purpose library for the same job, and code that uses one member can use another member instead.
Typical jobs: schema validation, key-value storage, HTTP client, ID generation, mutex, dependency injection, color math, date formatting, archive handling, logging.

Do not report these cases:
- Packages that work together, such as a framework with its plugin, adapter, or type package.
- Packages that each serve a different runtime or a different product, when the package list shows that separation.
- Build tools, lint tools, test tools, and bundler plugins.
- Packages from one family that ship as separate modules, such as \`@xsai/*\` or \`@pixi/*\`.

For each group, name the canonical package. Prefer a package from the preferred list. If no member is preferred, prefer the member that most files import.
List each other member as an alternative, with one sentence that tells why the canonical package can replace it.
`.trim()

export function buildMixedLibrariesPrompt(preferred: readonly string[], usage: string): string {
return [
`Preferred packages: ${preferred.join(', ') || 'none'}`,
`Packages, with the number of importing files and the packages that import them most:\n${usage}`,
].join('\n\n')
}
Loading
Loading