@kainappsinc/factory 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Lets tools that need the classic TypeScript compiler API run in a repository whose `typescript`
3
+ * is 7.0 (the native Go compiler).
4
+ *
5
+ * TypeScript 7.0's npm package has no JavaScript compiler API (`require('typescript')` returns only
6
+ * its version). typescript-eslint needs that API (TypeScript <6.1), and dependency-cruiser supports
7
+ * TypeScript <7 and >=7.1, not 7.0. The classic compiler is installed for these tools only, under
8
+ * an alias (`"typescript-classic": "npm:typescript@~6.0.3"` in devDependencies), and
9
+ * useClassicTypeScript makes `typescript` mean that alias for the rest of the process. `tsc` (the
10
+ * typecheck) still runs TypeScript 7: node_modules/typescript is untouched.
11
+ *
12
+ * Call it before anything loads `typescript`, and load the tool with a dynamic `await import()`:
13
+ * the dependencies of a static import are evaluated before the importing module's own body. (The
14
+ * officially suggested `"typescript": "npm:@typescript/typescript6"` swap does not install
15
+ * correctly under Bun 1.3: its nested `npm:typescript@^6` dependency resolves back to the alias.)
16
+ *
17
+ * How, per runtime:
18
+ * - Bun: a runtime plugin loads the classic compiler in place of the installed package's entry
19
+ * module and its package.json (dependency-cruiser reads the version there). It covers
20
+ * `require('typescript')` and `import 'typescript'`, wherever the process was started. Not
21
+ * covered: subpaths the installed package lacks, such as `typescript/lib/tsserverlibrary`
22
+ * (typescript-eslint's project service, used only by type-aware linting).
23
+ * Not a CommonJS resolver hook: Bun calls an overridden Module._resolveFilename without the
24
+ * requiring module, so every CommonJS lookup in the process would run from the working
25
+ * directory (and, where that has no node_modules, fetch from the registry).
26
+ * - Node: a CommonJS resolver hook redirects `require('typescript')` and `require('typescript/…')`.
27
+ * ES-module imports are not covered.
28
+ * Delete this module and the alias once the root `typescript` is 7.1 or later and typescript-eslint
29
+ * supports it.
30
+ *
31
+ * Generic (ts-bun pack): no project imports. The alias and `typescript` are resolved from this
32
+ * module's location.
33
+ */
34
+ import Module, { createRequire } from 'node:module';
35
+ import { readFileSync } from 'node:fs';
36
+ import { dirname } from 'node:path';
37
+
38
+ /** The alias the classic compiler is installed under. */
39
+ export const CLASSIC_ALIAS = 'typescript-classic';
40
+
41
+ type Resolve = (request: string, ...rest: unknown[]) => string;
42
+ type Classic = Record<string, unknown> & { version?: unknown; createProgram?: unknown };
43
+ const installed = new Set<string>();
44
+
45
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
46
+
47
+ function installBunPlugin(alias: string, classic: Classic, manifest: Record<string, unknown>): void {
48
+ const here = dirname(new URL(import.meta.url).pathname);
49
+ const replaced = new Map<string, Record<string, unknown>>();
50
+ for (const [request, exports] of [['typescript', classic], ['typescript/package.json', manifest]] as const) {
51
+ let path: string;
52
+ try {
53
+ path = Bun.resolveSync(request, here);
54
+ } catch {
55
+ continue; // no `typescript` installed: nothing to replace
56
+ }
57
+ replaced.set(path, { ...exports, default: exports });
58
+ }
59
+ if (!replaced.size) return;
60
+ const filter = new RegExp(`^(${[...replaced.keys()].map(escapeRegExp).join('|')})$`);
61
+ Bun.plugin({
62
+ name: `classic-typescript:${alias}`,
63
+ setup(build) {
64
+ build.onLoad({ filter }, ({ path }) => ({ exports: replaced.get(path) ?? {}, loader: 'object' }));
65
+ },
66
+ });
67
+ }
68
+
69
+ function installNodeHook(alias: string): void {
70
+ // Module._resolveFilename is CommonJS's internal resolver (not in the typings).
71
+ const resolve = Reflect.get(Module, '_resolveFilename') as Resolve;
72
+ Reflect.set(Module, '_resolveFilename', function (this: unknown, request: string, ...rest: unknown[]): string {
73
+ const redirected = request === 'typescript' || request.startsWith('typescript/') ? alias + request.slice('typescript'.length) : request;
74
+ return resolve.call(this, redirected, ...rest);
75
+ });
76
+ }
77
+
78
+ /**
79
+ * Makes `typescript` mean the classic compiler installed as `alias` for the rest of this process
80
+ * (see the header for what each runtime covers). Returns the classic version. Idempotent per alias.
81
+ */
82
+ export function useClassicTypeScript(alias: string = CLASSIC_ALIAS): string {
83
+ const require = createRequire(import.meta.url);
84
+ let classic: Classic;
85
+ let manifest: Record<string, unknown>;
86
+ try {
87
+ classic = require(alias) as Classic;
88
+ manifest = require(`${alias}/package.json`) as Record<string, unknown>;
89
+ } catch (e) {
90
+ throw new Error(`the classic TypeScript API is needed: add "${alias}": "npm:typescript@~6.0.3" to devDependencies (${(e as Error).message})`);
91
+ }
92
+ if (typeof classic.createProgram !== 'function') throw new Error(`"${alias}" has no classic compiler API; pin it to typescript <6.1`);
93
+ if (!installed.has(alias)) {
94
+ installed.add(alias);
95
+ if (typeof Bun === 'undefined') installNodeHook(alias);
96
+ else installBunPlugin(alias, classic, manifest);
97
+ }
98
+ return String(classic.version);
99
+ }
100
+
101
+ /**
102
+ * useClassicTypeScript for a tool that loads `typescript` with an ES-module import
103
+ * (dependency-cruiser): refuses to run where that is not covered (anything but Bun).
104
+ */
105
+ export function useClassicTypeScriptForImports(alias: string = CLASSIC_ALIAS): string {
106
+ if (typeof Bun === 'undefined') throw new Error('useClassicTypeScriptForImports needs Bun (a runtime plugin)');
107
+ return useClassicTypeScript(alias);
108
+ }
109
+
110
+ /**
111
+ * Bun only. Whether the `typescript` installed for `from` (default: this module's location) lacks the
112
+ * classic compiler API, so a tool that needs it must get it through useClassicTypeScript. False
113
+ * when no `typescript` is installed (nothing to replace). Decided without loading `typescript` in
114
+ * this process, so a later useClassicTypeScript still takes effect: before 7.0 the API is always
115
+ * there; from 7.0 a child process checks for `createProgram`.
116
+ */
117
+ export function needsClassicTypeScript(from: string = dirname(new URL(import.meta.url).pathname)): boolean {
118
+ let manifestPath: string;
119
+ try {
120
+ manifestPath = Bun.resolveSync('typescript/package.json', from);
121
+ } catch {
122
+ return false;
123
+ }
124
+ const major = majorVersion(manifestPath);
125
+ if (Number.isInteger(major) && major < 7) return false;
126
+ const probe = "process.stdout.write(typeof require('typescript').createProgram)";
127
+ const proc = Bun.spawnSync([process.execPath, '--no-install', '-e', probe], { cwd: from, stdout: 'pipe', stderr: 'pipe', timeout: 20_000 });
128
+ return proc.stdout.toString() !== 'function';
129
+ }
130
+
131
+ /** The major version in a package.json, or NaN when it cannot be read. */
132
+ function majorVersion(manifestPath: string): number {
133
+ let manifest: unknown;
134
+ try {
135
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
136
+ } catch {
137
+ return Number.NaN;
138
+ }
139
+ const version = typeof manifest === 'object' && manifest !== null ? Reflect.get(manifest, 'version') : undefined;
140
+ return typeof version === 'string' ? Number.parseInt(version, 10) : Number.NaN;
141
+ }
142
+
143
+ /**
144
+ * useClassicTypeScriptForImports only when the installed `typescript` lacks the compiler API
145
+ * (needsClassicTypeScript); returns the classic version, or null when the installed one is used.
146
+ */
147
+ export function useClassicTypeScriptIfNeeded(alias: string = CLASSIC_ALIAS): string | null {
148
+ return needsClassicTypeScript() ? useClassicTypeScriptForImports(alias) : null;
149
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * The command-line shell shared by the ts-bun counters (eslint-counts.ts, depcruise-counts.ts):
3
+ * argument parsing, stable key order and the exit codes a factory `run` ratchet relies on.
4
+ * Generic (ts-bun pack): no project imports.
5
+ */
6
+
7
+ export interface ParsedFlags {
8
+ /** The last value given for each value flag, by flag (`--config` → `values['--config']`). */
9
+ values: Partial<Record<string, string>>;
10
+ /** Comma-separated `--show` keys, trimmed, empties dropped. */
11
+ show?: string[];
12
+ /** Non-flag arguments, or `['.']` when there are none. */
13
+ positionals: string[];
14
+ }
15
+
16
+ /** Parses `argv` where every flag takes a value; `--show` is always one. Returns an error message on bad input. */
17
+ export function parseFlags(argv: readonly string[], valueFlags: readonly string[]): ParsedFlags | string {
18
+ const parsed: ParsedFlags = { values: {}, positionals: [] };
19
+ for (let i = 0; i < argv.length; i++) {
20
+ const a = argv[i]!;
21
+ if (a === '--show' || valueFlags.includes(a)) {
22
+ const v = argv[++i];
23
+ if (v === undefined || v.startsWith('--')) return `${a} needs a value`;
24
+ if (a === '--show') parsed.show = v.split(',').map((k) => k.trim()).filter(Boolean);
25
+ else parsed.values[a] = v;
26
+ } else if (a.startsWith('--')) {
27
+ return `unknown option ${a}`;
28
+ } else {
29
+ parsed.positionals.push(a);
30
+ }
31
+ }
32
+ if (!parsed.positionals.length) parsed.positionals.push('.');
33
+ return parsed;
34
+ }
35
+
36
+ /** Code-unit order (not locale order), so the printed key order is stable everywhere. */
37
+ export function compareKeys(a: string, b: string): number {
38
+ if (a < b) return -1;
39
+ if (a > b) return 1;
40
+ return 0;
41
+ }
42
+
43
+ /** The counts as a plain object with its keys in compareKeys order. */
44
+ export function sortedCounts(counts: Map<string, number>): Record<string, number> {
45
+ return Object.fromEntries([...counts].sort(([a], [b]) => compareKeys(a, b)));
46
+ }
47
+
48
+ /**
49
+ * Runs one counter: a usage error exits 2, a failure in `run` exits 1 with its message, otherwise
50
+ * `run`'s output is printed and the exit code is 0. Messages are prefixed with `name`.
51
+ */
52
+ export async function runCounter<T>(
53
+ name: string,
54
+ usage: string,
55
+ parsed: T | string,
56
+ run: (opts: T) => Promise<string>,
57
+ ): Promise<number> {
58
+ if (typeof parsed === 'string') {
59
+ process.stderr.write(`${name}: ${parsed}\nusage: ${usage}\n`);
60
+ return 2;
61
+ }
62
+ try {
63
+ process.stdout.write(await run(parsed));
64
+ return 0;
65
+ } catch (e) {
66
+ process.stderr.write(`${name}: ${e instanceof Error ? e.message : String(e)}\n`);
67
+ return 1;
68
+ }
69
+ }
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * dependency-cruiser counts for a factory `run` ratchet (ts-bun pack; generic, no project imports).
4
+ *
5
+ * factory-depcruise-counts [--config <file>] [<path>...]
6
+ * factory-depcruise-counts [--config <file>] --show <rules> [<path>...]
7
+ *
8
+ * Cruises `<path>`s (default ".") with the rules in `--config` (default .dependency-cruiser.cjs)
9
+ * and the tsconfig its `options.tsConfig` names (aliases come from that file's paths). Prints one
10
+ * JSON object: every `forbidden` rule by name with its violation count, 0 included, so a rule's
11
+ * first violation is an increase on a known key (`ratchet --against` allows new keys). Rules may
12
+ * share a name; their counts add up. One more key always appears:
13
+ * (unresolved) imports (other than node builtins) that resolve to no file: a broken alias or
14
+ * path would otherwise hide edges and read as fewer violations
15
+ * Severity `ignore` and the `allowed` rule set are not counted (forbidden rules only).
16
+ *
17
+ * `--show r1,r2` prints `from -> to` per violation of those rules (cycles with their path), each
18
+ * rule's `comment` once, and exits 0. A failed cruise, a config without forbidden rules, or no
19
+ * TypeScript transpiler exits 1. Bun only. When the installed `typescript` has no compiler API
20
+ * (7.0), the classic one is loaded through classic-typescript.ts (the `typescript-classic` alias).
21
+ */
22
+ import { resolve } from 'node:path';
23
+ import type { ICruiseResult, IConfiguration, IForbiddenRuleType, IViolation } from 'dependency-cruiser';
24
+ import { useClassicTypeScriptIfNeeded } from './classic-typescript.js';
25
+ import { compareKeys, parseFlags, runCounter, sortedCounts } from './counter-cli.js';
26
+
27
+ export const UNRESOLVED = '(unresolved)';
28
+
29
+ const USAGE = 'depcruise-counts.ts [--config <file>] [--show <rules>] [<path>...]';
30
+
31
+ export interface Options { config: string; paths: string[]; show?: string[] }
32
+
33
+ export function parseArgs(argv: readonly string[]): Options | string {
34
+ const parsed = parseFlags(argv, ['--config']);
35
+ if (typeof parsed === 'string') return parsed;
36
+ const { '--config': config = '.dependency-cruiser.cjs' } = parsed.values;
37
+ return { config, paths: parsed.positionals, ...(parsed.show !== undefined && { show: parsed.show }) };
38
+ }
39
+
40
+ /** An import that names a file (relative or through an alias) and resolves to none. */
41
+ function isUnresolved(d: { couldNotResolve: boolean; coreModule: boolean; module: string }): boolean {
42
+ return d.couldNotResolve && !d.coreModule;
43
+ }
44
+
45
+ /** Counts per rule name (every forbidden rule present, 0 included) plus (unresolved). */
46
+ export function countViolations(result: ICruiseResult, rules: readonly Pick<IForbiddenRuleType, 'name' | 'severity'>[]): Record<string, number> {
47
+ const counts = new Map<string, number>([[UNRESOLVED, 0]]);
48
+ for (const r of rules) if (r.severity !== 'ignore') counts.set(r.name ?? 'unnamed', 0);
49
+ for (const v of result.summary.violations) {
50
+ if (v.rule.severity === 'ignore' || !counts.has(v.rule.name)) continue;
51
+ counts.set(v.rule.name, counts.get(v.rule.name)! + 1);
52
+ }
53
+ for (const m of result.modules) {
54
+ for (const d of m.dependencies) if (isUnresolved(d)) counts.set(UNRESOLVED, counts.get(UNRESOLVED)! + 1);
55
+ }
56
+ return sortedCounts(counts);
57
+ }
58
+
59
+ function describe(v: IViolation): string {
60
+ if (v.cycle?.length) return `${v.from} -> ${v.cycle.map((c) => c.name).join(' -> ')}`;
61
+ if (v.via?.length) return `${v.from} -> ${v.via.map((c) => c.name).join(' -> ')}`;
62
+ const type = v.dependencyTypes?.some((t) => t === 'type-only' || t === 'type-import') ? ' (type only)' : '';
63
+ return `${v.from} -> ${v.to}${type}`;
64
+ }
65
+
66
+ /** `--show`: per asked rule, its comment and its violations sorted by from, to. */
67
+ export function formatShow(result: ICruiseResult, rules: readonly Pick<IForbiddenRuleType, 'name' | 'comment'>[], keys: readonly string[]): string {
68
+ const out: string[] = [];
69
+ for (const key of keys) {
70
+ const lines = result.summary.violations.filter((v) => v.rule.name === key).map(describe).sort(compareKeys);
71
+ if (key === UNRESOLVED) {
72
+ for (const m of result.modules) for (const d of m.dependencies) {
73
+ if (isUnresolved(d)) lines.push(`${m.source} -> ${d.module} (no such file)`);
74
+ }
75
+ }
76
+ const comment = rules.find((r) => r.name === key && r.comment)?.comment;
77
+ out.push(`${key}: ${lines.length} violation${lines.length === 1 ? '' : 's'}${comment ? `\n ${comment}` : ''}`);
78
+ for (const l of lines) out.push(` ${l}`);
79
+ }
80
+ return `${out.join('\n')}\n`;
81
+ }
82
+
83
+ /** Loads the config the way the depcruise CLI does (extends, tsconfig paths) and cruises. */
84
+ export async function cruisePaths(opts: Options): Promise<{ result: ICruiseResult; rules: IForbiddenRuleType[] }> {
85
+ useClassicTypeScriptIfNeeded();
86
+ const { cruise, getAvailableTranspilers } = await import('dependency-cruiser');
87
+ if (!getAvailableTranspilers().some((t) => t.name === 'typescript' && t.available)) {
88
+ throw new Error('dependency-cruiser found no TypeScript transpiler, so it would miss TypeScript imports');
89
+ }
90
+ const { default: extractConfig } = await import('dependency-cruiser/config-utl/extract-depcruise-config');
91
+ const { default: extractTSConfig } = await import('dependency-cruiser/config-utl/extract-ts-config');
92
+ const config = (await extractConfig(resolve(opts.config))) as IConfiguration;
93
+ const rules = config.forbidden ?? [];
94
+ if (!rules.length) throw new Error(`${opts.config} has no forbidden rules`);
95
+ const options = { ...config.options, ruleSet: config, validate: true };
96
+ const tsFile = options.tsConfig?.fileName;
97
+ if (options.webpackConfig) throw new Error('options.webpackConfig is not supported here; put aliases in the tsconfig paths');
98
+ const transpileOptions = tsFile ? { tsConfig: extractTSConfig(tsFile) } : {};
99
+ const reported = await cruise(opts.paths, options, {}, transpileOptions);
100
+ if (typeof reported.output === 'string') throw new Error('dependency-cruiser returned a report, not a result');
101
+ const result = reported.output;
102
+ if (!result.modules.some((m) => m.dependencies.length > 0)) throw new Error(`no imports found under ${opts.paths.join(' ')}`);
103
+ return { result, rules };
104
+ }
105
+
106
+ export async function main(argv: readonly string[]): Promise<number> {
107
+ return runCounter('depcruise-counts', USAGE, parseArgs(argv), async (opts) => {
108
+ const { result, rules } = await cruisePaths(opts);
109
+ if (opts.show) return formatShow(result, rules, opts.show);
110
+ return `${JSON.stringify(countViolations(result, rules), null, 2)}\n`;
111
+ });
112
+ }
113
+
114
+ if (import.meta.main) process.exit(await main(process.argv.slice(2)));
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * ESLint counts for a factory `run` ratchet (ts-bun pack; generic, no project imports).
4
+ *
5
+ * factory-eslint-counts [--cwd <dir>] [--config <file>] [<pattern>...]
6
+ * factory-eslint-counts [--cwd <dir>] [--config <file>] --show <keys> [<pattern>...]
7
+ *
8
+ * Lints `<pattern>`s (default ".") with the ESLint installed for `--cwd` (default: the current
9
+ * directory; else this script's own) and that directory's config, or `--config`. Prints one JSON
10
+ * object: every rule enabled (error or warn) in any linted file's calculated config, with its
11
+ * count, 0 included, so a rule's first violation is an increase on a known key rather than a new
12
+ * key (`ratchet --against` allows new keys). Three more keys always appear:
13
+ * (parse-error) fatal messages (a file ESLint could not parse is not linted at all)
14
+ * (unused-directive) disable directives that disable nothing
15
+ * (suppressed) problems hidden by disable directives: disabling a rule still counts
16
+ *
17
+ * `--show k1,k2` prints `file:line:col key message` for those keys instead (the ratchet's
18
+ * `show:` command), and exits 0. Any ESLint failure (bad config, no files) exits 1.
19
+ */
20
+ import { createRequire } from 'node:module';
21
+ import { resolve } from 'node:path';
22
+ import { pathToFileURL } from 'node:url';
23
+ import type { ESLint as ESLintClass, Linter } from 'eslint';
24
+ import { parseFlags, runCounter, sortedCounts } from './counter-cli.js';
25
+
26
+ export const PARSE_ERROR = '(parse-error)';
27
+ export const UNUSED_DIRECTIVE = '(unused-directive)';
28
+ export const SUPPRESSED = '(suppressed)';
29
+
30
+ const USAGE = 'eslint-counts.ts [--cwd <dir>] [--config <file>] [--show <keys>] [<pattern>...]';
31
+
32
+ export interface Options { cwd: string; config?: string; patterns: string[]; show?: string[] }
33
+
34
+ export function parseArgs(argv: readonly string[]): Options | string {
35
+ const parsed = parseFlags(argv, ['--cwd', '--config']);
36
+ if (typeof parsed === 'string') return parsed;
37
+ const { '--cwd': cwd = '.', '--config': config } = parsed.values;
38
+ return {
39
+ cwd,
40
+ patterns: parsed.positionals,
41
+ ...(config !== undefined && { config }),
42
+ ...(parsed.show !== undefined && { show: parsed.show }),
43
+ };
44
+ }
45
+
46
+ /** The key one message counts under. */
47
+ export function messageKey(m: Pick<Linter.LintMessage, 'ruleId' | 'fatal'>): string {
48
+ if (m.fatal) return PARSE_ERROR;
49
+ return m.ruleId ?? UNUSED_DIRECTIVE;
50
+ }
51
+
52
+ function isEnabled(entry: Linter.RuleEntry | undefined): boolean {
53
+ const level = Array.isArray(entry) ? entry[0] : entry;
54
+ return level === 1 || level === 2 || level === 'warn' || level === 'error';
55
+ }
56
+
57
+ /**
58
+ * Counts per key from lint results; `rules` is every rule enabled for at least one file.
59
+ * Returns the keys sorted, all enabled rules present.
60
+ */
61
+ export function countResults(results: readonly ESLintClass.LintResult[], rules: Iterable<string>): Record<string, number> {
62
+ const counts = new Map<string, number>([[PARSE_ERROR, 0], [UNUSED_DIRECTIVE, 0], [SUPPRESSED, 0]]);
63
+ for (const rule of rules) counts.set(rule, 0);
64
+ const add = (key: string, n = 1) => counts.set(key, (counts.get(key) ?? 0) + n);
65
+ for (const r of results) {
66
+ for (const m of r.messages) if (m.severity > 0) add(messageKey(m));
67
+ add(SUPPRESSED, r.suppressedMessages.length);
68
+ }
69
+ return sortedCounts(counts);
70
+ }
71
+
72
+ /** The ESLint class installed for `cwd` (the version its config expects), else this script's own. */
73
+ async function loadEslint(cwd: string): Promise<typeof ESLintClass> {
74
+ let path: string;
75
+ try {
76
+ path = createRequire(resolve(cwd, 'package.json')).resolve('eslint');
77
+ } catch {
78
+ path = createRequire(import.meta.url).resolve('eslint');
79
+ }
80
+ const mod = (await import(pathToFileURL(path).href)) as { ESLint: typeof ESLintClass };
81
+ return mod.ESLint;
82
+ }
83
+
84
+ export async function lint(opts: Options): Promise<{ results: ESLintClass.LintResult[]; rules: Set<string> }> {
85
+ const cwd = resolve(opts.cwd);
86
+ const ESLint = await loadEslint(cwd);
87
+ const eslint = new ESLint({ cwd, ...(opts.config !== undefined && { overrideConfigFile: resolve(opts.config) }) });
88
+ const results = await eslint.lintFiles(opts.patterns);
89
+ const rules = new Set<string>();
90
+ for (const r of results) {
91
+ const config = (await eslint.calculateConfigForFile(r.filePath)) as Linter.Config | undefined;
92
+ for (const [id, entry] of Object.entries(config?.rules ?? {})) if (isEnabled(entry)) rules.add(id);
93
+ }
94
+ return { results, rules };
95
+ }
96
+
97
+ /** `--show`: the occurrences of `keys`, one per line, sorted by file and line. */
98
+ export function formatShow(results: readonly ESLintClass.LintResult[], keys: readonly string[], cwd: string): string {
99
+ const want = new Set(keys);
100
+ const lines: string[] = [];
101
+ const rel = (file: string) => (file.startsWith(`${cwd}/`) ? file.slice(cwd.length + 1) : file);
102
+ for (const r of [...results].sort((a, b) => (a.filePath < b.filePath ? -1 : 1))) {
103
+ const found = [
104
+ ...r.messages.filter((m) => m.severity > 0).map((m) => ({ m, key: messageKey(m) })),
105
+ ...r.suppressedMessages.map((m) => ({ m, key: SUPPRESSED })),
106
+ ].filter((x) => want.has(x.key)).sort((a, b) => a.m.line - b.m.line || a.m.column - b.m.column);
107
+ for (const { m, key } of found) {
108
+ const what = key === SUPPRESSED ? `${m.ruleId ?? '?'} (disabled inline)` : m.message;
109
+ lines.push(`${rel(r.filePath)}:${m.line}:${m.column} ${key} ${what}`);
110
+ }
111
+ }
112
+ return lines.length ? `${lines.join('\n')}\n` : `no occurrences of ${keys.join(', ')}\n`;
113
+ }
114
+
115
+ export async function main(argv: readonly string[]): Promise<number> {
116
+ return runCounter('eslint-counts', USAGE, parseArgs(argv), async (opts) => {
117
+ const { results, rules } = await lint(opts);
118
+ if (opts.show) return formatShow(results, opts.show, resolve(opts.cwd));
119
+ return `${JSON.stringify(countResults(results, rules), null, 2)}\n`;
120
+ });
121
+ }
122
+
123
+ if (import.meta.main) process.exit(await main(process.argv.slice(2)));