diff --git a/packages/plugin-js/README.md b/packages/plugin-js/README.md index 8049dae..5d9d34e 100644 --- a/packages/plugin-js/README.md +++ b/packages/plugin-js/README.md @@ -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. diff --git a/packages/plugin-js/src/index.test.ts b/packages/plugin-js/src/index.test.ts index 48662a9..4358171 100644 --- a/packages/plugin-js/src/index.test.ts +++ b/packages/plugin-js/src/index.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest' import plugin, { configFileTestsRule, duplicatedKnowledgeRule, + mixedLibrariesRule, overlappingEntrypointsRule, redundantCatchRule, singleUseMaterializationRule, @@ -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') + }) }) diff --git a/packages/plugin-js/src/index.ts b/packages/plugin-js/src/index.ts index 947b886..defe575 100644 --- a/packages/plugin-js/src/index.ts +++ b/packages/plugin-js/src/index.ts @@ -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' @@ -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' @@ -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, diff --git a/packages/plugin-js/src/rules/no-mixed-libraries/imports.test.ts b/packages/plugin-js/src/rules/no-mixed-libraries/imports.test.ts new file mode 100644 index 0000000..8766c7d --- /dev/null +++ b/packages/plugin-js/src/rules/no-mixed-libraries/imports.test.ts @@ -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' }, + ]) + }) +}) diff --git a/packages/plugin-js/src/rules/no-mixed-libraries/imports.ts b/packages/plugin-js/src/rules/no-mixed-libraries/imports.ts new file mode 100644 index 0000000..3f11133 --- /dev/null +++ b/packages/plugin-js/src/rules/no-mixed-libraries/imports.ts @@ -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] +} diff --git a/packages/plugin-js/src/rules/no-mixed-libraries/index.ts b/packages/plugin-js/src/rules/no-mixed-libraries/index.ts new file mode 100644 index 0000000..d0e573a --- /dev/null +++ b/packages/plugin-js/src/rules/no-mixed-libraries/index.ts @@ -0,0 +1,2 @@ +export { mixedLibrariesPrompt } from './prompt' +export { mixedLibrariesRule } from './rule' diff --git a/packages/plugin-js/src/rules/no-mixed-libraries/prompt.ts b/packages/plugin-js/src/rules/no-mixed-libraries/prompt.ts new file mode 100644 index 0000000..a6f8c7b --- /dev/null +++ b/packages/plugin-js/src/rules/no-mixed-libraries/prompt.ts @@ -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') +} diff --git a/packages/plugin-js/src/rules/no-mixed-libraries/rule.test.ts b/packages/plugin-js/src/rules/no-mixed-libraries/rule.test.ts new file mode 100644 index 0000000..5e9193f --- /dev/null +++ b/packages/plugin-js/src/rules/no-mixed-libraries/rule.test.ts @@ -0,0 +1,246 @@ +import type { Buffer } from 'node:buffer' +import type { AddressInfo } from 'node:net' + +import type { DiagnosticDescriptor, FileTarget, RuleContext } from '@alint-js/plugin' + +import type { MixedLibrariesOptions } from './rule' + +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' + +import { createSourceRuntime } from '@alint-js/core' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { mixedLibrariesRule } from './rule' + +interface Group { + alternatives: { name: string, reason: string }[] + canonical: string + purpose: string +} + +/* A real server answers the model call rather than a stub, so the request the rule sends stays under test. */ +let baseURL: string +let close: () => Promise +let requests: Record[] +let groups: Group[] +let cwd: string + +const WORKSPACE: Record = { + 'package.json': JSON.stringify({ name: 'repo' }), + 'packages/api/src/order.ts': 'import { object } from \'valibot\'\n', + 'packages/api/src/user.ts': 'import * as v from \'valibot\'\nimport type { Node } from \'@types/node\'\n', + 'packages/app/package.json': JSON.stringify({ name: '@repo/app' }), + 'packages/app/src/form.ts': 'import { object, string } from \'valibot\'\nimport type { Buffer } from \'node:buffer\'\n', + 'packages/app/src/schema.ts': [ + 'import { z } from \'zod\'', + 'import { shared } from \'@repo/app/shared\'', + '', + 'export const user = z.object({ name: z.string() })', + 'export const again = await import(\'zod\')', + ].join('\n'), +} + +beforeEach(async () => { + requests = [] + groups = [] + cwd = await mkdtemp(join(tmpdir(), 'mixed-libraries-')) + for (const [path, text] of Object.entries(WORKSPACE)) { + await mkdir(dirname(join(cwd, path)), { recursive: true }) + await writeFile(join(cwd, path), text) + } + + const server = createServer((request, response) => { + let payload = '' + request.on('data', (chunk: Buffer) => { + payload += chunk.toString() + }) + request.on('end', () => { + requests.push(JSON.parse(payload) as Record) + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify(completion(groups))) + }) + }) + + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + baseURL = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1` + close = async () => new Promise((done, fail) => server.close(error => error + ? fail(error) + : done())) +}) + +afterEach(async () => { + await close() + await rm(cwd, { force: true, recursive: true }) +}) + +function completion(reported: Group[]): unknown { + return { + choices: [ + { + finish_reason: 'tool_calls', + message: { + content: null, + role: 'assistant', + tool_calls: [ + { + function: { + arguments: JSON.stringify({ groups: reported }), + name: 'reportFindings', + }, + id: 'call_1', + type: 'function', + }, + ], + }, + }, + ], + usage: { completion_tokens: 5, prompt_tokens: 11, total_tokens: 16 }, + } +} + +/** One context is one run: the review is shared through `src`. */ +function createRun(options: { allow?: string[][], preferred?: string[] } = {}) { + const diagnostics: DiagnosticDescriptor[] = [] + const context: RuleContext = { + cwd, + id: 'js/no-mixed-libraries', + localId: 'no-mixed-libraries', + logger: { + debug: () => {}, + }, + metering: { + recordUsage: () => {}, + }, + model: () => Promise.resolve({ + aliases: [], + capabilities: ['tool-call'], + id: 'test-model', + name: 'test-model', + params: {}, + provider: { + endpoint: baseURL, + headers: {}, + id: 'test-provider', + type: 'openai-compatible', + }, + }), + options: [ + { allow: options.allow ?? [], preferred: options.preferred ?? [] }, + ], + report: diagnostic => void diagnostics.push(diagnostic), + settings: {}, + src: createSourceRuntime({ + readFile: async () => { throw new Error('the rule reads files from disk') }, + }), + } + const rule = mixedLibrariesRule.create(context) + + return { + diagnostics, + lint: async (relativePath: string) => { + const path = join(cwd, relativePath) + const target: FileTarget = { + file: { contentHash: 'unused', language: 'typescript', path }, + identity: `file:${path}`, + kind: 'file', + language: 'typescript', + } + await rule.onTargetFile?.(target) + }, + } +} + +function userPrompt(): string { + const messages = requests[0].messages as { content: string, role: string }[] + return messages.filter(message => message.role === 'user').map(message => message.content).join('\n') +} + +const ZOD_AND_VALIBOT: Group = { + alternatives: [ + { name: 'valibot', reason: 'Both validate schemas.' }, + ], + canonical: 'zod', + purpose: 'schema validation', +} + +describe('no-mixed-libraries', () => { + it('reports every import of the replaced package in the linted file', async () => { + groups = [ZOD_AND_VALIBOT] + const run = createRun({ + preferred: ['valibot'], + }) + + await run.lint('packages/app/src/schema.ts') + + // The preferred package wins over the canonical package that the model chose. + expect(run.diagnostics.map(diagnostic => diagnostic.loc?.start.line)).toEqual([1, 5]) + expect(run.diagnostics[0].message).toContain('`zod` duplicates `valibot` (schema validation)') + expect(run.diagnostics[0].message).toContain('`valibot` has 3 importing files and `zod` has 1') + expect(run.diagnostics[0].evidence).toEqual({ canonical: 'valibot', suggestion: 'Use `valibot` instead of `zod`.' }) + }) + + it('asks the model one time for a run, and reports nothing in a file that imports only the canonical package', async () => { + groups = [ZOD_AND_VALIBOT] + const run = createRun({ + preferred: ['valibot'], + }) + + await run.lint('packages/app/src/form.ts') + await run.lint('packages/app/src/schema.ts') + await run.lint('packages/api/src/user.ts') + + expect(requests).toHaveLength(1) + expect(run.diagnostics.every(diagnostic => diagnostic.filePath?.endsWith('schema.ts'))).toBe(true) + }) + + it('lists only external packages, with their file counts and directories', async () => { + const run = createRun({ + preferred: ['valibot'], + }) + + await run.lint('packages/app/src/form.ts') + + const prompt = userPrompt() + expect(prompt).toContain('Preferred packages: valibot') + expect(prompt).toContain('valibot: 3 files (packages/api 2, packages/app 1)') + expect(prompt).toContain('zod: 1 files (packages/app 1)') + // Workspace packages, type packages, and built-in modules are not library choices. + expect(prompt).not.toContain('@repo/app') + expect(prompt).not.toContain('@types/node') + expect(prompt).not.toContain('node:buffer') + }) + + it('drops a group that names a package no file imports', async () => { + groups = [ + { + ...ZOD_AND_VALIBOT, + alternatives: [ + ...ZOD_AND_VALIBOT.alternatives, + { name: 'yup', reason: 'Invented.' }, + ], + }, + ] + const run = createRun() + + await run.lint('packages/app/src/form.ts') + + expect(run.diagnostics).toEqual([]) + }) + + it('reports nothing for a group that an allow set covers', async () => { + groups = [ZOD_AND_VALIBOT] + const run = createRun({ + allow: [ + ['valibot', 'zod'], + ], + preferred: ['valibot'], + }) + + await run.lint('packages/app/src/schema.ts') + + expect(run.diagnostics).toEqual([]) + }) +}) diff --git a/packages/plugin-js/src/rules/no-mixed-libraries/rule.ts b/packages/plugin-js/src/rules/no-mixed-libraries/rule.ts new file mode 100644 index 0000000..e8284cc --- /dev/null +++ b/packages/plugin-js/src/rules/no-mixed-libraries/rule.ts @@ -0,0 +1,275 @@ +import type { RuleContext } from '@alint-js/plugin' +import type { InferOutput } from 'valibot' + +import type { PackageImport } from './imports' + +import { readFile } from 'node:fs/promises' +import { dirname, relative, resolve } from 'node:path' + +import { formatOutputLanguageInstruction, generateStructured } from '@alint-js/core/structured-output' +import { defineRule } from '@alint-js/plugin' +import { DEFAULT_IGNORE_PATTERNS, listFiles } from '@alint-js/tools-fs' +import { array, description, object, optional, pipe, string } from 'valibot' + +import { extractPackageImports } from './imports' +import { buildMixedLibrariesPrompt, mixedLibrariesPrompt } from './prompt' + +export interface MixedLibraryFinding { + /** The package that the repository keeps. */ + canonical: string + /** The package to replace. */ + name: string + purpose: string + reason: string +} + +/** Package name -> absolute file path -> the imports of that package in that file. */ +export type PackageUsage = Map> + +export const mixedLibrariesResponseSchema = pipe( + object({ + groups: array(object({ + alternatives: array(object({ + name: pipe(string(), description('Package name, exactly as listed.')), + reason: pipe(string(), description('One sentence. Why the canonical package can replace this package.')), + })), + canonical: pipe(string(), description('Package name, exactly as listed.')), + purpose: pipe(string(), description('The shared job, in a few lowercase words.')), + })), + }), + description('Report the groups of overlapping packages. Report an empty list if there are none.'), +) + +const optionsSchema = optional(object({ + /** Sets of packages that can coexist. A group inside one set is not reported. */ + allow: optional(array(array(string())), []), + /** Packages that the repository has chosen. One of them becomes the canonical member of its group. */ + preferred: optional(array(string()), []), +}), {}) + +export type MixedLibrariesOptions = NonNullable> + +interface Review { + findings: MixedLibraryFinding[] + usage: PackageUsage +} + +/* + * The review is a fact about the workspace, not about one file, so it runs once per run: the + * first file that asks builds it, and every other file reuses it. `ctx.src` is the one object a + * run shares across rule instances, the same key the simplicity index uses. + */ +const reviews = new WeakMap>() + +/** + * Reports the imports of a library when the repository also uses another library for the same job. + * + * The usage index covers every JavaScript, TypeScript, and Vue file in the workspace, so a run on + * changed files sees the same groups as a full run. Diagnostics go only to the linted files. + */ +export const mixedLibrariesRule = defineRule({ + // The verdict depends on every file in the workspace, not only on the linted target. + cache: false, + create: (ctx) => { + const [{ allow, preferred }] = ctx.options + + return { + async onTargetFile(target) { + let review = reviews.get(ctx.src) + if (review === undefined) { + review = reviewWorkspace(ctx, { allow, preferred }) + reviews.set(ctx.src, review) + } + + const { findings, usage } = await review + const filePath = resolve(ctx.cwd, target.file.path) + + for (const finding of findings) { + for (const found of usage.get(finding.name)?.get(filePath) ?? []) { + ctx.report({ + evidence: { + canonical: finding.canonical, + suggestion: `Use \`${finding.canonical}\` instead of \`${finding.name}\`.`, + }, + filePath: target.file.path, + loc: { + start: { column: 0, line: found.line }, + }, + message: `\`${finding.name}\` duplicates \`${finding.canonical}\` (${finding.purpose}). \`${finding.canonical}\` has ${usage.get(finding.canonical)?.size ?? 0} importing files and \`${finding.name}\` has ${usage.get(finding.name)?.size ?? 0}. ${finding.reason}`, + }) + } + } + }, + } + }, + languages: 'any', + options: [optionsSchema], +}) + +/** + * One line for each package, most imported first, with the directories that import it most. + * + * The directories tell the model whether two packages serve different products, for example one + * in a server and one in a browser app, which the prompt says not to report. + */ +export function formatUsage(cwd: string, usage: PackageUsage): string { + return [...usage] + .sort(([, left], [, right]) => right.size - left.size) + .map(([name, files]) => { + const directories = new Map() + for (const filePath of files.keys()) { + const directory = topDirectoryOf(relative(cwd, filePath)) + directories.set(directory, (directories.get(directory) ?? 0) + 1) + } + + const top = [...directories] + .sort(([, left], [, right]) => right - left) + .slice(0, 4) + .map(([directory, count]) => `${directory} ${count}`) + + return `${name}: ${files.size} files (${top.join(', ')})` + }) + .join('\n') +} + +/** + * Turns the model's groups into one finding for each package to replace. + * + * A group is dropped when it names a package that no file imports, because the model can invent a + * name, and when an `allow` set covers every member. A preferred member overrides the canonical + * package that the model chose. + */ +export function resolveGroups( + groups: { alternatives: { name: string, reason: string }[], canonical: string, purpose: string }[], + usage: PackageUsage, + options: { allow: readonly (readonly string[])[], preferred: readonly string[] }, +): MixedLibraryFinding[] { + const findings: MixedLibraryFinding[] = [] + + for (const group of groups) { + const members = [ + group.canonical, + ...group.alternatives.map(alternative => alternative.name), + ] + if (members.some(name => !usage.has(name))) + continue + if (options.allow.some(allowed => members.every(name => allowed.includes(name)))) + continue + + const canonical = members.find(name => options.preferred.includes(name)) ?? group.canonical + const reasons = new Map(group.alternatives.map(alternative => [alternative.name, alternative.reason])) + + for (const name of members) { + if (name !== canonical) { + findings.push({ + canonical, + name, + purpose: group.purpose, + reason: reasons.get(name) ?? '', + }) + } + } + } + + return findings +} + +/** + * Collects the external package imports of every source file in the workspace. + * + * Packages of the workspace itself are not library choices, so every `package.json` name is left + * out. Type packages are left out too: `@types/x` always comes with `x`. + */ +async function collectUsage(cwd: string): Promise { + const ignore = [...DEFAULT_IGNORE_PATTERNS] + const workspacePackages = new Set() + for (const manifest of await listFiles(cwd, { + ignore, + patterns: ['**/package.json'], + })) { + const name = await readPackageName(manifest) + if (name !== undefined) + workspacePackages.add(name) + } + + const usage: PackageUsage = new Map() + const files = await listFiles(cwd, { + ignore, + patterns: ['**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,vue}'], + }) + + for (const filePath of files.sort()) { + for (const found of extractPackageImports(await readFile(filePath, 'utf8'))) { + if (workspacePackages.has(found.name) || found.name.startsWith('@types/')) + continue + + const byFile = usage.get(found.name) ?? new Map() + byFile.set(filePath, [ + ...byFile.get(filePath) ?? [], + found, + ]) + usage.set(found.name, byFile) + } + } + + return usage +} + +async function readPackageName(manifest: string): Promise { + try { + const parsed: unknown = JSON.parse(await readFile(manifest, 'utf8')) + return typeof parsed === 'object' && parsed !== null && 'name' in parsed && typeof parsed.name === 'string' + ? parsed.name + : undefined + } + catch { + // A broken manifest names no package. The rule reviews imports, not manifests. + return undefined + } +} + +async function reviewWorkspace(ctx: RuleContext, options: MixedLibrariesOptions): Promise { + const usage = await collectUsage(ctx.cwd) + if (usage.size < 2) + return { findings: [], usage } + + const { groups } = await generateStructured({ + createMessages: retryFeedback => [ + { + content: [ + mixedLibrariesPrompt, + formatOutputLanguageInstruction(ctx.outputLanguage), + ].filter(Boolean).join('\n\n'), + role: 'system', + }, + { + content: buildMixedLibrariesPrompt(options.preferred, formatUsage(ctx.cwd, usage)), + role: 'user', + }, + ...(retryFeedback === undefined + ? [] + : [ + { content: retryFeedback, role: 'user' as const }, + ]), + ], + logger: ctx.logger, + metering: ctx.metering, + model: await ctx.model(), + operation: 'mixed-libraries-judge', + schema: mixedLibrariesResponseSchema, + signal: ctx.signal, + }) + + return { + findings: resolveGroups(groups, usage, options), + usage, + } +} + +/** `packages/ui/src/a.ts` -> `packages/ui`, `src/a.ts` -> `src`, `a.ts` -> `.` */ +function topDirectoryOf(relativePath: string): string { + const directory = dirname(relativePath) + return directory === '.' + ? '.' + : directory.split(/[\\/]/).slice(0, 2).join('/') +} diff --git a/packages/plugin-simplicity/README.md b/packages/plugin-simplicity/README.md index 736b1ee..f872c80 100644 --- a/packages/plugin-simplicity/README.md +++ b/packages/plugin-simplicity/README.md @@ -121,6 +121,7 @@ question. - **`simplicity/no-duplicated-helper`**: a small helper is defined in two or more places. - **`simplicity/no-needless-helper`**: a one-line helper that does not earn its existence. +- **`simplicity/no-reinvented-helper`**: a small helper that a utility library of the repository already exports. Rule ids carry the prefix you give the plugin in `plugins`, which is `simplicity/` in every example here. @@ -186,6 +187,53 @@ its keep. The same three lines, two rules, opposite decisions. It costs one model call per file rather than an agent loop, because everything the judgement needs is already in hand and there is nothing to search for. +## `no-reinvented-helper` + +`no-duplicated-helper` finds a helper written twice in the workspace. This rule finds a helper +that the workspace did not need to write: a utility library that the repository already depends +on exports the same function. + +``` +Helper "clampValue" reimplements `clamp` from `es-toolkit`. Both bound a number to a range. +``` + +It has no default, because only the repository knows which libraries it chose. Name them in +the rule options, and the rule is off until you do: + +```js +import simplicityPlugin from '@alint-js/plugin-simplicity' + +import { defineConfig } from '@alint-js/cli' + +export default defineConfig([ + { + files: ['**/*.{js,jsx,ts,tsx,mjs,cjs,mts,cts}'], + plugins: { simplicity: simplicityPlugin }, + rules: { + 'simplicity/no-reinvented-helper': [ + 'warn', + { + libraries: ['es-toolkit'] + } + ], + }, + }, +]) +``` + +It reads the export names from the library itself, loaded from the linted workspace, so they +match the installed version. A finding that names a helper outside the file, a library outside +the options, or an export that the library does not have is dropped: the model can invent all +three. Loading a library runs its top-level code, so list only the libraries you trust. + +It disagrees with `no-needless-helper` on purpose. `clamp(value, low, high)` earns its +existence there, because the name says more than the body. Here it is still reported when the +library exports `clamp`, because the workspace can import the name instead of keeping the body. + +It uses the same index of small helpers and the same `settings.simplicity` options. It costs one +model call per file that has a helper, and the core cache keeps the verdict until the file or the +options change. A library upgrade that adds an export does not reach a cached file. + ## Usage The rules read whole files and parse them internally, so they take plain-text targets: diff --git a/packages/plugin-simplicity/src/index.ts b/packages/plugin-simplicity/src/index.ts index fc96012..58b6a27 100644 --- a/packages/plugin-simplicity/src/index.ts +++ b/packages/plugin-simplicity/src/index.ts @@ -2,6 +2,7 @@ import { definePlugin } from '@alint-js/plugin' import { duplicatedHelperRule } from './rules/no-duplicated-helper' import { needlessHelperRule } from './rules/no-needless-helper' +import { reinventedHelperRule } from './rules/no-reinvented-helper' export { alphaFingerprint, exactFingerprint, normalizedBody, tokenize, tokenOverlap } from './fingerprint' export type { IndexedHelper, RepoIndex, RepoIndexOptions, ReviewCache } from './repo' @@ -19,6 +20,13 @@ export { needlessHelperResponseSchema, needlessHelperRule, } from './rules/no-needless-helper' +export type { ReinventedHelperOptions } from './rules/no-reinvented-helper' +export { + buildReinventedHelperPrompt, + reinventedHelperPrompt, + reinventedHelperResponseSchema, + reinventedHelperRule, +} from './rules/no-reinvented-helper' export type { SimplicitySettings } from './rules/shared/settings' export const simplicityPlugin = definePlugin({ @@ -45,6 +53,8 @@ export const simplicityPlugin = definePlugin({ rules: { 'no-duplicated-helper': duplicatedHelperRule, 'no-needless-helper': needlessHelperRule, + // Not in `recommended`: it has no default, because only the repository knows its libraries. + 'no-reinvented-helper': reinventedHelperRule, }, }) diff --git a/packages/plugin-simplicity/src/repo/index.ts b/packages/plugin-simplicity/src/repo/index.ts index 1f33d0a..f472916 100644 --- a/packages/plugin-simplicity/src/repo/index.ts +++ b/packages/plugin-simplicity/src/repo/index.ts @@ -65,7 +65,7 @@ export function helpersIn(index: RepoIndex, filePath: string): IndexedHelper[] { return index.helpers.filter(helper => helper.filePath === filePath) } -export async function repoIndexFor(ctx: RuleContext, options: RepoIndexOptions): Promise { +export async function repoIndexFor(ctx: RuleContext, options: RepoIndexOptions): Promise { const existing = indexes.get(ctx.src) if (existing !== undefined) { @@ -110,7 +110,7 @@ export function twinsOf( return (bucket.get(fingerprint) ?? []).filter(other => other.id !== helper.id) } -async function buildRepoIndex(ctx: RuleContext, options: RepoIndexOptions): Promise { +async function buildRepoIndex(ctx: RuleContext, options: RepoIndexOptions): Promise { const index: RepoIndex = { byAlpha: new Map(), byExact: new Map(), @@ -192,7 +192,7 @@ function functionInfoOf(target: SourceTarget): FunctionInfo | undefined { } async function helpersOf( - ctx: RuleContext, + ctx: RuleContext, filePath: string, options: RepoIndexOptions, calls: Map, diff --git a/packages/plugin-simplicity/src/rules/no-reinvented-helper/exports.ts b/packages/plugin-simplicity/src/rules/no-reinvented-helper/exports.ts new file mode 100644 index 0000000..856a0ae --- /dev/null +++ b/packages/plugin-simplicity/src/rules/no-reinvented-helper/exports.ts @@ -0,0 +1,118 @@ +import type { RuleContext } from '@alint-js/plugin' + +import { access, readFile } from 'node:fs/promises' +import { createRequire } from 'node:module' +import { dirname, join } from 'node:path' +import { pathToFileURL } from 'node:url' + +import { errorMessageFrom } from '@moeru/std/error' + +/* + * The export names come from the library itself, not from the model, so a finding can be checked + * against them. The library is resolved from the linted workspace, so the names match the version + * that the workspace depends on. + * + * Importing a library runs its top-level code. Utility libraries have none worth noting, and the + * rule only imports the libraries that its options name. + */ +const resolved = new WeakMap>>() + +/** The runtime export names of `library`, or undefined when the workspace cannot load it. */ +export function libraryExports(ctx: RuleContext, library: string): Promise { + let byName = resolved.get(ctx.src) + if (byName === undefined) { + byName = new Map() + resolved.set(ctx.src, byName) + } + + let loading = byName.get(library) + if (loading === undefined) { + loading = loadExports(ctx, library) + byName.set(library, loading) + } + + return loading +} + +async function exists(path: string): Promise { + try { + await access(path) + return true + } + catch { + return false + } +} + +async function loadExports(ctx: RuleContext, library: string): Promise { + try { + const module: Record = await import(pathToFileURL(await resolveEntry(ctx.cwd, library)).href) + + return Object.keys(module).filter(name => name !== 'default' && name !== '__esModule').sort() + } + catch (error) { + ctx.logger.debug(`no-reinvented-helper: could not load ${library}: ${errorMessageFrom(error) ?? 'unknown error'}`) + + return undefined + } +} + +/* + * `require.resolve` finds most packages, but it rejects a package whose `exports` map has only an + * `import` condition. Such a package is ESM only, so its manifest gives the entry instead. The + * manifest is found by walking the same `node_modules` directories that Node searches, because + * `exports` can also hide `./package.json` from `require.resolve`. + */ +async function resolveEntry(cwd: string, library: string): Promise { + const require = createRequire(join(cwd, 'package.json')) + + try { + return require.resolve(library) + } + catch { + for (const directory of require.resolve.paths(library) ?? []) { + const manifestPath = join(directory, library, 'package.json') + if (!await exists(manifestPath)) + continue + + const manifest: { exports?: unknown, main?: string, module?: string } = JSON.parse(await readFile(manifestPath, 'utf8')) + const entry = rootExport(manifest.exports) ?? manifest.module ?? manifest.main + if (entry === undefined) + throw new Error(`${library} declares no root entry`) + + return join(dirname(manifestPath), entry) + } + + throw new Error(`${library} is not installed in the workspace`) + } +} + +function rootExport(exports: unknown): string | undefined { + if (typeof exports === 'string') + return exports + if (typeof exports !== 'object' || exports === null) + return undefined + + const map = exports as Record + const root = '.' in map + ? map['.'] + : map + if (typeof root === 'string') + return root + if (typeof root !== 'object' || root === null) + return undefined + + for (const condition of ['import', 'default', 'node']) { + const target = condition in root + ? (root as Record)[condition] + : undefined + if (typeof target === 'string') + return target + // A nested condition, for example `import: { types, default }`. + const nested = rootExport(target) + if (nested !== undefined) + return nested + } + + return undefined +} diff --git a/packages/plugin-simplicity/src/rules/no-reinvented-helper/index.ts b/packages/plugin-simplicity/src/rules/no-reinvented-helper/index.ts new file mode 100644 index 0000000..d5844ad --- /dev/null +++ b/packages/plugin-simplicity/src/rules/no-reinvented-helper/index.ts @@ -0,0 +1,3 @@ +export { buildReinventedHelperPrompt, reinventedHelperPrompt } from './prompt' +export { reinventedHelperResponseSchema, reinventedHelperRule } from './rule' +export type { ReinventedHelperOptions } from './rule' diff --git a/packages/plugin-simplicity/src/rules/no-reinvented-helper/prompt.ts b/packages/plugin-simplicity/src/rules/no-reinvented-helper/prompt.ts new file mode 100644 index 0000000..1c3ce3f --- /dev/null +++ b/packages/plugin-simplicity/src/rules/no-reinvented-helper/prompt.ts @@ -0,0 +1,23 @@ +import type { IndexedHelper } from '../../repo' + +export const reinventedHelperPrompt = ` +You review small local helpers. The repository already depends on the utility libraries listed below. +Find each helper that reimplements one export of these libraries. + +Report a helper only when all of these are true: +- The helper is a general utility. It has no domain logic, and it does not read module state. +- One listed export has the same behavior for the inputs that the helper accepts. +- A caller can replace the helper with that export and keep the result. + +Do not report a helper that adds a type guard, a default, an error message, or a domain rule that the export does not have. +Do not report a helper that already calls the export. +Use a library and an export name exactly as listed. If you are not sure that the export exists, do not report. +`.trim() + +/** The libraries with their export names, then the helpers, each numbered so a finding can name the one it means. */ +export function buildReinventedHelperPrompt(libraries: ReadonlyMap, candidates: readonly IndexedHelper[]): string { + return [ + ...[...libraries].map(([library, names]) => `Exports of \`${library}\`:\n${names.join(', ')}`), + ...candidates.map((helper, index) => `Helper ${index + 1}: \`${helper.name}\`\n${helper.text}`), + ].join('\n\n') +} diff --git a/packages/plugin-simplicity/src/rules/no-reinvented-helper/rule.test.ts b/packages/plugin-simplicity/src/rules/no-reinvented-helper/rule.test.ts new file mode 100644 index 0000000..16939f4 --- /dev/null +++ b/packages/plugin-simplicity/src/rules/no-reinvented-helper/rule.test.ts @@ -0,0 +1,234 @@ +import type { Buffer } from 'node:buffer' +import type { AddressInfo } from 'node:net' + +import type { DiagnosticDescriptor, FileTarget, RuleContext } from '@alint-js/plugin' + +import type { ReinventedHelperOptions } from './rule' + +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' + +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +import { createFixtureContext, createFixtureRuntime } from '../../repo/fixtures' +import { reinventedHelperRule } from './rule' + +interface Finding { + exportName: string + helper: number + library: string + name: string + reason: string +} + +/* A real server answers the model call rather than a stub, so the request the rule sends stays under test. */ +let baseURL: string +let close: () => Promise +let requests: Record[] +let findings: Finding[] +let cwd: string + +/* + * A workspace with its own library. Its `exports` map has only an `import` condition, so + * `require.resolve` rejects it and the rule must read the entry from the manifest. + */ +const WORKSPACE: Record = { + 'node_modules/tiny-utils/index.js': [ + 'export const clamp = (value, min, max) => Math.min(Math.max(value, min), max)', + 'export const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))', + ].join('\n'), + 'node_modules/tiny-utils/package.json': JSON.stringify({ + exports: { + '.': { import: './index.js' }, + }, + name: 'tiny-utils', + type: 'module', + }), + 'package.json': JSON.stringify({ name: 'repo', type: 'module' }), + 'src/helpers.ts': [ + 'export function clampValue(value: number, min: number, max: number): number {', + ' return Math.min(Math.max(value, min), max)', + '}', + '', + 'export function greeting(name: string): string {', + ' return name.trim().replace(/\\s+/g, \' \') + \' is back\'', + '}', + ].join('\n'), +} + +beforeEach(async () => { + requests = [] + findings = [] + cwd = await mkdtemp(join(tmpdir(), 'simplicity-reinvented-')) + for (const [path, text] of Object.entries(WORKSPACE)) { + await mkdir(dirname(join(cwd, path)), { recursive: true }) + await writeFile(join(cwd, path), text) + } + + const server = createServer((request, response) => { + let payload = '' + request.on('data', (chunk: Buffer) => { + payload += chunk.toString() + }) + request.on('end', () => { + requests.push(JSON.parse(payload) as Record) + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify(completion(findings))) + }) + }) + + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + baseURL = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1` + close = async () => new Promise((done, fail) => server.close(error => error + ? fail(error) + : done())) +}) + +afterEach(async () => { + await close() + await rm(cwd, { force: true, recursive: true }) +}) + +function completion(reported: Finding[]): unknown { + return { + choices: [ + { + finish_reason: 'tool_calls', + message: { + content: null, + role: 'assistant', + tool_calls: [ + { + function: { + arguments: JSON.stringify({ findings: reported }), + name: 'reportFindings', + }, + id: 'call_1', + type: 'function', + }, + ], + }, + }, + ], + usage: { completion_tokens: 5, prompt_tokens: 11, total_tokens: 16 }, + } +} + +async function lint(libraries: string[], settings: Record = { + simplicity: { cache: false }, +}) { + const diagnostics: DiagnosticDescriptor[] = [] + const context = createFixtureContext({ + cwd, + model: () => Promise.resolve({ + aliases: [], + capabilities: ['tool-call'], + id: 'test-model', + name: 'test-model', + params: {}, + provider: { + endpoint: baseURL, + headers: {}, + id: 'test-provider', + type: 'openai-compatible', + }, + }), + report: diagnostic => void diagnostics.push(diagnostic), + settings, + src: createFixtureRuntime(), + }) as unknown as RuleContext + const path = join(cwd, 'src/helpers.ts') + const target: FileTarget = { + file: { contentHash: 'unused', language: 'typescript', path }, + identity: `file:${path}`, + kind: 'file', + language: 'typescript', + } + + await reinventedHelperRule.create({ + ...context, + options: [ + { libraries }, + ], + }).onTargetFile?.(target) + + return diagnostics +} + +function userPrompt(): string { + const messages = requests[0].messages as { content: string, role: string }[] + return messages.filter(message => message.role === 'user').map(message => message.content).join('\n') +} + +describe('no-reinvented-helper', () => { + it('lists the real exports of the library and the helpers of the file', async () => { + await lint(['tiny-utils']) + + expect(requests).toHaveLength(1) + const prompt = userPrompt() + expect(prompt).toContain('Exports of `tiny-utils`:\nclamp, sleep') + expect(prompt).toContain('Helper 1: `clampValue`') + expect(prompt).toContain('Helper 2: `greeting`') + }) + + it('reports a helper that the model matches to a listed export', async () => { + findings = [ + { + exportName: 'clamp', + helper: 1, + library: 'tiny-utils', + name: 'clampValue', + reason: 'Both bound a number to a range.', + }, + ] + + const diagnostics = await lint(['tiny-utils']) + + expect(diagnostics).toHaveLength(1) + expect(diagnostics[0].loc?.start.line).toBe(1) + expect(diagnostics[0].message).toBe('Helper "clampValue" reimplements `clamp` from `tiny-utils`. Both bound a number to a range.') + expect(diagnostics[0].evidence).toEqual({ export: 'clamp', library: 'tiny-utils', reason: 'Both bound a number to a range.' }) + }) + + it('drops a finding that names an export, a library, or a helper that does not exist', async () => { + findings = [ + { + exportName: 'clampNumber', + helper: 1, + library: 'tiny-utils', + name: 'clampValue', + reason: 'Invented export.', + }, + { + exportName: 'clamp', + helper: 1, + library: 'other-utils', + name: 'clampValue', + reason: 'Invented library.', + }, + { + exportName: 'clamp', + helper: 3, + library: 'tiny-utils', + name: 'boundValue', + reason: 'Invented helper.', + }, + ] + + expect(await lint(['tiny-utils'])).toEqual([]) + }) + + it('asks nothing when no listed library can be loaded', async () => { + expect(await lint(['missing-utils'])).toEqual([]) + expect(requests).toEqual([]) + }) + + it('asks nothing when settings.simplicity.judge is false', async () => { + expect(await lint(['tiny-utils'], { + simplicity: { cache: false, judge: false }, + })).toEqual([]) + expect(requests).toEqual([]) + }) +}) diff --git a/packages/plugin-simplicity/src/rules/no-reinvented-helper/rule.ts b/packages/plugin-simplicity/src/rules/no-reinvented-helper/rule.ts new file mode 100644 index 0000000..3f94371 --- /dev/null +++ b/packages/plugin-simplicity/src/rules/no-reinvented-helper/rule.ts @@ -0,0 +1,157 @@ +import type { RuleContext } from '@alint-js/plugin' +import type { InferOutput } from 'valibot' + +import type { IndexedHelper } from '../../repo' + +import { formatOutputLanguageInstruction, generateStructured } from '@alint-js/core/structured-output' +import { defineRule } from '@alint-js/plugin' +import { errorMessageFrom } from '@moeru/std/error' +import { minimatch } from 'minimatch' +import { relative } from 'pathe' +import { array, description, minLength, number, object, pipe, string } from 'valibot' + +import { helpersIn, repoIndexFor } from '../../repo' +import { resolveFinding } from '../no-needless-helper/rule' +import { readSimplicitySettings } from '../shared/settings' +import { libraryExports } from './exports' +import { buildReinventedHelperPrompt, reinventedHelperPrompt } from './prompt' + +export const reinventedHelperResponseSchema = object({ + findings: array(object({ + exportName: pipe(string(), description('The export name, exactly as listed.')), + helper: pipe(number(), description('The number shown beside the helper, exactly as given.')), + library: pipe(string(), description('The library, exactly as listed.')), + name: pipe(string(), description('The helper\'s name, exactly as shown.')), + reason: pipe(string(), description('One sentence. Why the export has the same behavior.')), + })), +}) + +const optionsSchema = object({ + /** The utility libraries that the repository depends on, for example `['es-toolkit']`. */ + libraries: pipe(array(string()), minLength(1)), +}) + +export type ReinventedHelperOptions = InferOutput + +/** + * Reports a small helper when a utility library that the repository already depends on exports + * the same function. + * + * `no-duplicated-helper` finds a helper written twice in the workspace. This rule finds a helper + * that the workspace did not need to write. It uses the same index of small helpers, so the same + * `settings.simplicity` options apply. + */ +export const reinventedHelperRule = defineRule({ + /* + * The verdict depends on the helpers of this file and on the library exports. The core cache + * keys on the file and the options, so a library upgrade that adds an export reaches a cached + * file only after the file changes. + */ + cacheKey: reinventedHelperPrompt, + create: (ctx) => { + const settings = readSimplicitySettings(ctx) + const [{ libraries }] = ctx.options + + return { + async onTargetFile(target) { + if (!settings.judge || settings.ignores.some(pattern => minimatch(relative(ctx.cwd, target.file.path), pattern, { dot: true }))) { + return + } + + const index = await repoIndexFor(ctx, { + cwd: ctx.cwd, + ignores: settings.ignores, + maxLines: settings.maxLines, + minTokens: settings.minTokens, + }) + const candidates = helpersIn(index, target.file.path) + + if (candidates.length === 0) { + return + } + + const exports = new Map() + for (const library of libraries) { + const names = await libraryExports(ctx, library) + if (names !== undefined && names.length > 0) + exports.set(library, names) + } + + if (exports.size === 0) { + return + } + + await judge(ctx, candidates, exports) + }, + } + }, + // Nothing here reads syntax, only the helpers that the index extracts, as in `no-needless-helper`. + languages: 'any', + options: [optionsSchema], +}) + +async function judge( + ctx: RuleContext, + candidates: readonly IndexedHelper[], + exports: ReadonlyMap, +): Promise { + let findings + + try { + ({ findings } = await generateStructured({ + createMessages: retryFeedback => [ + { + content: [ + reinventedHelperPrompt, + formatOutputLanguageInstruction(ctx.outputLanguage), + ].filter(Boolean).join('\n\n'), + role: 'system', + }, + { + content: buildReinventedHelperPrompt(exports, candidates), + role: 'user', + }, + ...(retryFeedback === undefined + ? [] + : [ + { content: retryFeedback, role: 'user' as const }, + ]), + ], + logger: ctx.logger, + metering: ctx.metering, + model: await ctx.model(), + operation: 'no-reinvented-helper-judge', + schema: reinventedHelperResponseSchema, + signal: ctx.signal, + })) + } + catch (error) { + ctx.logger.debug(`no-reinvented-helper: could not judge the helpers: ${errorMessageFrom(error) ?? 'unknown error'}`) + + return + } + + for (const finding of findings) { + const resolution = resolveFinding(candidates, finding) + + // The model can invent a helper, a library, or an export. Each must exist before a report. + if (resolution.outcome !== 'resolved' || !exports.get(finding.library)?.includes(finding.exportName)) { + ctx.logger.debug(`no-reinvented-helper: ignored a finding for "${finding.name}" (${finding.library}#${finding.exportName}), which names no helper under review or no listed export`) + continue + } + + const { helper } = resolution + ctx.report({ + evidence: { + export: finding.exportName, + library: finding.library, + reason: finding.reason, + }, + filePath: helper.filePath, + loc: { + start: { column: 0, line: helper.line }, + }, + message: `Helper "${helper.name}" reimplements \`${finding.exportName}\` from \`${finding.library}\`. ${finding.reason}`, + }) + } +} diff --git a/packages/plugin-simplicity/src/rules/shared/settings.ts b/packages/plugin-simplicity/src/rules/shared/settings.ts index c93e930..0bca839 100644 --- a/packages/plugin-simplicity/src/rules/shared/settings.ts +++ b/packages/plugin-simplicity/src/rules/shared/settings.ts @@ -23,7 +23,7 @@ const settingsSchema = object({ export type SimplicitySettings = InferOutput -export function readSimplicitySettings(ctx: RuleContext): SimplicitySettings { +export function readSimplicitySettings(ctx: RuleContext): SimplicitySettings { const configured = ctx.settings.simplicity ?? {} // valibot's `object()` accepts an array, so `settings.simplicity: []` would pass and silently