@zgeoff/chex 0.5.0 → 0.6.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.
package/README.md CHANGED
@@ -16,8 +16,7 @@ Run each shared check of a zgeoff repo as one subcommand, and take the lefthook
16
16
  that calls them with one `extends` line.
17
17
 
18
18
  Each check prints its own findings, then `cleared: <check>` when it passes or `bounced: <check>`
19
- when it fails, so a run of several checks names each one that failed. To start, run `chex init`,
20
- then `chex length links`.
19
+ when it fails, so a run of several checks shows each one that failed.
21
20
 
22
21
  ## Install
23
22
 
@@ -26,42 +25,43 @@ bun add -d @zgeoff/chex @zgeoff/rig @zgeoff/diet @commitlint/cli @zgeoff/commitl
26
25
  bun x --no-install chex init
27
26
  ```
28
27
 
29
- `chex` runs under Bun. The baseline runs the related tests through [`@zgeoff/rig`](../rig/README.md)
30
- and each job under the memory cap of [`@zgeoff/diet`](../diet/README.md), so a repo that takes it
31
- installs both, and `chex init` fails until it does. `chex commits` lints commit messages with
32
- `@commitlint/cli` and `@zgeoff/commitlint-config`; in a repo that lacks either one, it prints a
33
- notice and passes.
28
+ `chex` runs under Bun. The pre-push baseline runs the related tests through
29
+ [`@zgeoff/rig`](../rig/README.md) and each job under the memory cap of
30
+ [`@zgeoff/diet`](../diet/README.md), so a repo that takes the baseline installs both, and
31
+ `chex init` fails until it does. In a repo that lacks `@commitlint/cli` or
32
+ `@zgeoff/commitlint-config`, `chex commits` prints a notice and passes.
34
33
 
35
34
  ## Commands
36
35
 
37
- `chex <check>...` runs each check in turn, even after one bounces, and exits with the highest exit
38
- code among them: 0 when each clears, 1 when a check finds a fault, and 2 when a check cannot run.
36
+ `chex <check>...` runs each check in turn, even after one fails, and exits with the highest exit
37
+ code among them: 0 when each passes, 1 when a check finds a fault, and 2 when a check cannot run.
39
38
  chex also exits 2 for a check that throws or exits with any other code, such as 127 for a missing
40
39
  program. `chex <check> <args...>` hands the arguments to that one check.
41
40
 
42
- The docs checks read the repo's READMEs, its `docs/` tree and its skills:
41
+ Run these docs checks on a repo's READMEs, its `docs/` tree and its skills:
43
42
 
44
43
  | Check | Fails on | Arguments |
45
44
  | --------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
46
- | `prose` | banned words, process residue and over-long paragraphs | the paths |
45
+ | `prose` | banned words, notes about how the doc was made and over-long paragraphs (needs `perl` and a `git` with PCRE, else exit 2) | the paths |
47
46
  | `length` | a README over its line limit, and warns on a doc over its cap | none |
48
47
  | `links` | a relative link or anchor that does not resolve | the paths |
49
48
  | `readmes` | a README of none of the [five kinds](https://github.com/zgeoff/skills/blob/main/skills/docs-writing/references/readmes.md#the-five-kinds) | none |
50
49
  | `vision` | a missing `docs/vision.md`, or one past 60 lines | none |
51
- | `skill` | a skill's frontmatter, its word limit, a link with a line anchor, and a coined term such as "the unit limit" | the skill dirs |
52
-
53
- The repo checks read the branch, the pushed commits and the repo's config:
54
-
55
- | Check | Fails on | Arguments |
56
- | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
57
- | `commits` | a pushed commit whose message fails `@zgeoff/commitlint-config` | `--pushed-refs` |
58
- | `local-paths` | a line a pushed commit adds that holds the home folder or the host name | `--pushed-refs` |
59
- | `test-timeouts` | a `bun test` timeout above its lane's limit, in a script or a `bunfig.toml` | none |
60
- | `test-layout` | a test folder, file name or import outside [the test layout](../../docs/guides/test-layout.md); test code includes a relative `[test] preload` file, a `.nix`-only `tests/` folder and a private workspace that only test code imports | none |
61
- | `workflows` | nothing: it prints each fault of the shared workflow lint, and fails when there is one | the paths |
62
- | `dependency-gates` | a stale age-gate exclude, an override or an audit ignore that nothing needs, a first-party package with no age-gate exclude, or a pinned release younger than the age gate ([details](../../docs/architecture/dependency-updates.md#the-dependency-gates-check)) | none |
63
- | `uncommitted` | a file the branch changes that holds a change the push does not send | none |
64
- | `pr-body` | a PR description with a heading, a label, a code block or a prose-check commit that the [PR template](../../.github/PULL_REQUEST_TEMPLATE.md) doesn't allow ([details](../../docs/architecture/pr-body-check.md)) | `--body-file`, then `--base` and `--head` for the commit checks |
50
+ | `skill` | a skill's frontmatter, its word limit, a link with a line anchor, and a made-up label for a rule, such as "the unit limit" | the skill dirs |
51
+
52
+ Run these repo checks on the branch, the pushed commits and the repo's config:
53
+
54
+ | Check | Fails on | Arguments |
55
+ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
56
+ | `commits` | a pushed commit whose message fails `@zgeoff/commitlint-config` | `--pushed-refs` |
57
+ | `local-paths` | a line a pushed commit adds that holds the home folder or the host name | `--pushed-refs` |
58
+ | `test-timeouts` | a `bun test` timeout above its lane's limit, in a script or a `bunfig.toml` | none |
59
+ | `lint-overrides` | an oxlint config that turns a `zgeoff/*` rule, `consistent-type-assertions` or `ban-ts-comment` off or down to a warning, a config in code (`oxlint.config.ts` or `.mts`), or a config that the last commit does not hold as a plain file or that does not parse; it reads each file or symlink named `.oxlintrc*.json` or `.oxlintrc*.jsonc`, each path a `package.json` script gives `oxlint` with `-c` or `--config`, the file each symlink reaches, and each file a config extends by a relative path | none |
60
+ | `test-layout` | a test folder, file name or import outside [the test layout](../../docs/guides/test-layout.md), where test code covers a relative `[test] preload` file, a `.nix`-only `tests/` folder and a private workspace that only test code imports | none |
61
+ | `workflows` | nothing: it prints each fault of the shared workflow lint, and fails when there is one | the paths |
62
+ | `dependency-gates` | a stale age-gate exclude, an override or an audit ignore that nothing needs, a first-party package with no age-gate exclude, or a pinned release younger than the age gate ([details](../../docs/architecture/dependency-updates.md#the-dependency-gates-check)) | none |
63
+ | `uncommitted` | a file the branch changes that has an uncommitted edit, which the push does not send | none |
64
+ | `pr-body` | a PR description with a heading, a label or a code block that the [PR template](../../.github/PULL_REQUEST_TEMPLATE.md) doesn't allow, or a Deslop or Cold read line with a commit hash the branch lacks or a later doc change outdates ([details](../../docs/architecture/pr-body-check.md)) | `--body-file`, then `--base` and `--head` for the commit checks |
65
65
 
66
66
  With no path, `prose` and `links` read every README outside `.claude/` and `.agents/`, every file
67
67
  under `docs/`, each spike's `results.md`, and the Markdown under `.agents/skills/`,
@@ -69,32 +69,31 @@ under `docs/`, each spike's `results.md`, and the Markdown under `.agents/skills
69
69
  stdin, as a pre-push hook gets them; without it, `commits` and `local-paths` read the branch's
70
70
  commits since its base.
71
71
 
72
- Some docs checks skip files whether or not you name paths, and a path you name never brings a
73
- skipped file back:
72
+ Some docs checks skip files even when you name them:
74
73
 
75
- - `prose` needs `perl` and a `git` with PCRE, and fails with exit 2 when it lacks one.
76
74
  - `prose` skips the `docs-writing`, `project-docs-writing`, `skill-writing` and `deslop` skills
77
- under `.agents/skills/`, `.claude/skills/`, `skills/` and `sync/skills/`, which hold the banned
78
- patterns as examples.
75
+ under `.agents/skills/`, `.claude/skills/`, `skills/` and `sync/skills/`, because those skills
76
+ hold the banned patterns as examples.
79
77
  - `links` skips `project-docs-writing` under `.agents/skills/` and `.claude/skills/`, and
80
78
  `docs-writing` and `skill-writing` under `.agents/skills/`, `.claude/skills/` and `sync/skills/`,
81
- which link to placeholder targets as examples.
79
+ because those skills link to placeholder targets as examples.
82
80
  - `prose`, `links`, `readmes` and `skill` skip each file that `.gitattributes` marks
83
81
  `linguist-vendored`.
84
82
 
85
83
  `chex init` writes the `extends` line and a
86
84
  [`chex-baseline` job](../../docs/architecture/pre-push-baseline.md#a-checkout-without-the-baseline)
87
85
  into `lefthook.yml`, adds a `check:docs` script of `chex prose length links readmes skill` when the
88
- repo has none, and changes nothing on a second run. `chex ci-plan` plans a run of `bun-checks`.
86
+ repo has none, and changes nothing on a second run. `chex ci-plan` plans a `bun-checks` run.
89
87
 
90
88
  ## The pre-push baseline
91
89
 
92
- A repo's `lefthook.yml` takes the baseline with one line, which `chex init` writes:
90
+ Add one line to a repo's `lefthook.yml` to take the baseline; `chex init` writes it:
93
91
 
94
92
  ```yaml
95
93
  extends:
96
94
  - node_modules/@zgeoff/chex/lefthook.yml
97
95
  ```
98
96
 
99
- Its jobs, [each described here](../../docs/architecture/pre-push-baseline.md), call `chex <check>`,
100
- `bun run check:docs`, `rig related` and the repo's own `format:check` and `typecheck` scripts.
97
+ The baseline's jobs, which [its doc](../../docs/architecture/pre-push-baseline.md) describes, call
98
+ `chex <check>`, `bun run check:docs`, `rig related` and the repo's own `format:check` and
99
+ `typecheck` scripts.
package/lefthook.yml CHANGED
@@ -139,6 +139,8 @@ pre-push:
139
139
  --pushed-refs # {files}'
140
140
  - name: chex-test-timeouts
141
141
  run: '{clear-git-env} bun x --no-install diet -- bun x --no-install chex test-timeouts'
142
+ - name: chex-lint-overrides
143
+ run: '{clear-git-env} bun x --no-install diet -- bun x --no-install chex lint-overrides'
142
144
  - name: chex-dependency-gates
143
145
  run: '{clear-git-env} bun x --no-install diet -- bun x --no-install chex dependency-gates'
144
146
  - name: chex-typecheck
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zgeoff/chex",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Run each shared docs and repo check as one subcommand, with the lefthook pre-push baseline that calls them",
5
5
  "keywords": [
6
6
  "checks",
@@ -77,20 +77,22 @@
77
77
  "typecheck": "tsrs --fast"
78
78
  },
79
79
  "dependencies": {
80
- "@zgeoff/std": "0.5.0",
81
- "oxc-parser": "0.159.0",
80
+ "@zgeoff/std": "0.6.0",
81
+ "oxc-parser": "0.160.0",
82
82
  "ts-pattern": "5.9.2"
83
83
  },
84
84
  "devDependencies": {
85
85
  "@types/bun": "1.4.4",
86
- "@zgeoff/rig": "0.3.4",
87
- "@zgeoff/std": "0.5.0",
88
- "@zgeoff/testing": "0.5.0",
86
+ "@zgeoff/oxlint-config": "0.13.0",
87
+ "@zgeoff/rig": "0.3.5",
88
+ "@zgeoff/std": "0.6.0",
89
+ "@zgeoff/testing": "0.5.1",
89
90
  "@zgeoff/tools-scripts": "0.0.0",
90
91
  "msw": "3.0.4",
91
92
  "tiny-invariant": "1.3.3",
92
93
  "tsrs": "0.25.0-ts7.1.0-beta",
93
- "typescript": "7.0.2"
94
+ "typescript": "7.0.2",
95
+ "zod": "4.6.7"
94
96
  },
95
97
  "engines": {
96
98
  "bun": ">=1.3"
@@ -6,6 +6,7 @@ export const checkNames = [
6
6
  'commits',
7
7
  'local-paths',
8
8
  'test-timeouts',
9
+ 'lint-overrides',
9
10
  'test-layout',
10
11
  'workflows',
11
12
  'dependency-gates',
package/src/cli.ts CHANGED
@@ -8,6 +8,7 @@ import { runChex } from './cli/run-chex.ts';
8
8
  import { runCommitsCommand } from './commits/run-commits-check.ts';
9
9
  import { runDependencyGatesCommand } from './dependency-gates/run-dependency-gates-check.ts';
10
10
  import { runInit } from './init/run-init.ts';
11
+ import { runLintOverridesCommand } from './lint-overrides/run-lint-overrides-check.ts';
11
12
  import { runLocalPathsCommand } from './local-paths/run-local-paths-check.ts';
12
13
  import { writeTextFile } from './output/write-text-file.ts';
13
14
  import { runPrBodyCheck } from './pr-body/run-pr-body-check.ts';
@@ -24,6 +25,7 @@ process.exitCode = await runChex(process.argv.slice(2), {
24
25
  commits: runCommitsCommand,
25
26
  'local-paths': runLocalPathsCommand,
26
27
  'test-timeouts': runTestTimeoutsCommand,
28
+ 'lint-overrides': runLintOverridesCommand,
27
29
  'test-layout': runTestLayoutCommand,
28
30
  workflows: runWorkflowsCommand,
29
31
  'dependency-gates': runDependencyGatesCommand,
@@ -0,0 +1,25 @@
1
+ import { posix } from 'node:path';
2
+ import type { TrackedTree, TreeEntry } from './types.ts';
3
+
4
+ export function buildTrackedTree(
5
+ entries: readonly TreeEntry[],
6
+ linkTargets: ReadonlyMap<string, string>,
7
+ ): TrackedTree {
8
+ const directories = new Set<string>();
9
+
10
+ for (const entry of entries) {
11
+ for (
12
+ let folder = posix.dirname(entry.path);
13
+ folder !== '.' && !directories.has(folder);
14
+ folder = posix.dirname(folder)
15
+ ) {
16
+ directories.add(folder);
17
+ }
18
+ }
19
+
20
+ return {
21
+ links: linkTargets,
22
+ files: new Set(entries.filter((entry) => !entry.isLink).map((entry) => entry.path)),
23
+ directories,
24
+ };
25
+ }
@@ -0,0 +1,193 @@
1
+ import { basename, posix } from 'node:path';
2
+ import { collectExtendsPaths } from './collect-extends-paths.ts';
3
+ import { collectLintOverrideFindings } from './collect-lint-override-findings.ts';
4
+ import { collectScriptConfigPaths } from './collect-script-config-paths.ts';
5
+ import { findLastEntry } from './find-last-entry.ts';
6
+ import type { JSONCTreeResult } from './parse-jsonc-tree.ts';
7
+ import { parseJSONCTree } from './parse-jsonc-tree.ts';
8
+ import { resolveTrackedPath } from './resolve-tracked-path.ts';
9
+ import type { ConfigReference, LintOverrideFinding, TrackedTree } from './types.ts';
10
+
11
+ export interface ConfigReport {
12
+ readonly findings: LintOverrideFinding[];
13
+
14
+ // The tracked files that the walk needs and `texts` lacks. The walk stops short at each of them,
15
+ // so the caller reads them and calls again.
16
+ readonly missing: string[];
17
+ }
18
+
19
+ const configPattern = /^\.?oxlintrc(?:\.[\w-]+)*\.jsonc?$/u;
20
+
21
+ // oxlint loads these configs in code, which chex cannot read.
22
+ const codeConfigNamePattern = /^oxlint\.config\.m?ts$/u;
23
+
24
+ // Walks every config that oxlint may read, as the files of HEAD. Each file is checked once, however
25
+ // many paths lead to it, and reported under the first of those paths in sorted order.
26
+ export function collectConfigReport(
27
+ tree: Readonly<TrackedTree>,
28
+ texts: ReadonlyMap<string, string>,
29
+ ): ConfigReport {
30
+ const missing = new Set<string>();
31
+
32
+ const findings: LintOverrideFinding[] = [];
33
+
34
+ const manifests = new Map<string, JSONCTreeResult>();
35
+
36
+ for (const path of [...tree.files].filter((file) => basename(file) === 'package.json')) {
37
+ const text = texts.get(path);
38
+
39
+ if (text === undefined) {
40
+ missing.add(path);
41
+ continue;
42
+ }
43
+
44
+ const result = parseJSONCTree(text);
45
+
46
+ manifests.set(path, result);
47
+
48
+ if (!result.isValid) {
49
+ findings.push({ path, message: unparseableMessage(result.reason) });
50
+ }
51
+ }
52
+
53
+ const isToolsRepo =
54
+ getManifestName(manifests, 'package.json') === 'tools' &&
55
+ getManifestName(manifests, 'packages/std/package.json') === '@zgeoff/std';
56
+
57
+ const scriptPaths = [...manifests].flatMap(([path, result]) =>
58
+ result.isValid ? collectScriptConfigPaths(path, result.root) : [],
59
+ );
60
+
61
+ const discovered = [...tree.files, ...tree.links.keys()]
62
+ .filter(
63
+ (path) => configPattern.test(basename(path)) || codeConfigNamePattern.test(basename(path)),
64
+ )
65
+ .map((path) => ({ path, isOptional: false }));
66
+
67
+ const walk = walkConfigs(tree, texts, [...discovered, ...scriptPaths]);
68
+
69
+ for (const file of walk.missing) {
70
+ missing.add(file);
71
+ }
72
+
73
+ for (const [file, labels] of walk.reached) {
74
+ const path = labels.toSorted()[0] ?? file;
75
+
76
+ findings.push(...collectFileFindings(path, file, walk.parsed.get(file), isToolsRepo));
77
+ }
78
+
79
+ findings.push(...walk.unreadable);
80
+
81
+ return {
82
+ findings: findings.toSorted(
83
+ (left, right) => Number(left.path > right.path) - Number(left.path < right.path),
84
+ ),
85
+ missing: [...missing],
86
+ };
87
+ }
88
+
89
+ function unparseableMessage(reason: string): string {
90
+ return `chex cannot parse this file (${reason}), and oxlint may read it; commit the config as a plain \`.oxlintrc.json\` file that parses`;
91
+ }
92
+
93
+ function getManifestName(manifests: ReadonlyMap<string, JSONCTreeResult>, path: string): string {
94
+ const result = manifests.get(path);
95
+
96
+ const name =
97
+ result?.isValid === true && result.root.kind === 'object'
98
+ ? findLastEntry(result.root.entries, 'name')?.value
99
+ : undefined;
100
+
101
+ return name?.kind === 'literal' ? name.text : '';
102
+ }
103
+
104
+ interface Walk {
105
+ readonly reached: ReadonlyMap<string, string[]>;
106
+ readonly parsed: ReadonlyMap<string, JSONCTreeResult>;
107
+ readonly unreadable: LintOverrideFinding[];
108
+ readonly missing: string[];
109
+ }
110
+
111
+ const codeFilePattern = /\.[cm]?[jt]s$/u;
112
+
113
+ const unreadableMessage =
114
+ 'oxlint may read this config, but chex cannot read it from HEAD; commit the config as a plain `.oxlintrc.json` file that HEAD holds';
115
+
116
+ // Follows each path through its links, then the `extends` of each file it reaches.
117
+ function walkConfigs(
118
+ tree: Readonly<TrackedTree>,
119
+ texts: ReadonlyMap<string, string>,
120
+ roots: readonly ConfigReference[],
121
+ ): Walk {
122
+ const reached = new Map<string, string[]>();
123
+ const parsed = new Map<string, JSONCTreeResult>();
124
+ const unreadable = new Map<string, LintOverrideFinding>();
125
+ const missing = new Set<string>();
126
+ const visited = new Set<string>();
127
+
128
+ const pending = [...roots];
129
+
130
+ for (let item = pending.pop(); item !== undefined; item = pending.pop()) {
131
+ if (visited.has(item.path)) {
132
+ continue;
133
+ }
134
+
135
+ visited.add(item.path);
136
+
137
+ const label = posix.normalize(item.path);
138
+ const file = resolveTrackedPath(item.path, tree);
139
+
140
+ if (file === null) {
141
+ if (!item.isOptional) {
142
+ unreadable.set(label, { path: label, message: unreadableMessage });
143
+ }
144
+
145
+ continue;
146
+ }
147
+
148
+ reached.set(file, [...(reached.get(file) ?? []), label]);
149
+
150
+ const text = texts.get(file);
151
+
152
+ if (codeFilePattern.test(basename(file))) {
153
+ continue;
154
+ }
155
+
156
+ if (text === undefined) {
157
+ missing.add(file);
158
+ continue;
159
+ }
160
+
161
+ const result = parsed.get(file) ?? parseJSONCTree(text);
162
+
163
+ parsed.set(file, result);
164
+
165
+ if (result.isValid) {
166
+ pending.push(...collectExtendsPaths(item.path, result.root));
167
+ }
168
+ }
169
+
170
+ return { reached, parsed, unreadable: [...unreadable.values()], missing: [...missing] };
171
+ }
172
+
173
+ const codeConfigMessage =
174
+ 'chex reads only JSON configs, so write the config as a plain `.oxlintrc.json` file that HEAD holds';
175
+
176
+ function collectFileFindings(
177
+ path: string,
178
+ file: string,
179
+ result: JSONCTreeResult | undefined,
180
+ isToolsRepo: boolean,
181
+ ): LintOverrideFinding[] {
182
+ if (codeFilePattern.test(basename(file))) {
183
+ return [{ path, message: codeConfigMessage }];
184
+ }
185
+
186
+ if (result === undefined) {
187
+ return [];
188
+ }
189
+
190
+ return result.isValid
191
+ ? collectLintOverrideFindings(path, result.root, isToolsRepo)
192
+ : [{ path, message: unparseableMessage(result.reason) }];
193
+ }
@@ -0,0 +1,31 @@
1
+ import { posix } from 'node:path';
2
+ import { findLastEntry } from './find-last-entry.ts';
3
+ import { joinRawPath } from './join-raw-path.ts';
4
+ import type { JSONCNode } from './parse-jsonc-tree.ts';
5
+ import type { ConfigReference } from './types.ts';
6
+
7
+ // oxlint resolves each entry against the folder of the config, so a link counts by its own folder.
8
+ // An entry that is no path, such as a package specifier, may name a tracked file, and otherwise
9
+ // names a package whose shared config sets the rules.
10
+ export function collectExtendsPaths(path: string, root: JSONCNode): ConfigReference[] {
11
+ const extendsEntry = root.kind === 'object' ? findLastEntry(root.entries, 'extends') : undefined;
12
+
13
+ if (extendsEntry?.value.kind !== 'array') {
14
+ return [];
15
+ }
16
+
17
+ return extendsEntry.value.items.flatMap((item) =>
18
+ item.kind === 'literal'
19
+ ? [
20
+ {
21
+ path: joinRawPath(posix.dirname(path), item.text),
22
+ isOptional: isPackageLike(item.text),
23
+ },
24
+ ]
25
+ : [],
26
+ );
27
+ }
28
+
29
+ function isPackageLike(entry: string): boolean {
30
+ return !/^(?:\.{1,2}(?:\/|$)|\/)/u.test(entry) || entry.split('/').includes('node_modules');
31
+ }
@@ -0,0 +1,120 @@
1
+ import { findLastEntry } from './find-last-entry.ts';
2
+ import type { JSONCEntry, JSONCNode } from './parse-jsonc-tree.ts';
3
+ import { stdHelperPaths } from './std-helper-paths.ts';
4
+ import type { LintOverrideFinding } from './types.ts';
5
+
6
+ export function collectLintOverrideFindings(
7
+ path: string,
8
+ root: JSONCNode,
9
+ isToolsRepo: boolean,
10
+ ): LintOverrideFinding[] {
11
+ return collectSettings(root, isToolsRepo).map((setting) => ({
12
+ path,
13
+ message: `line ${setting.line} sets ${setting.rule} to ${setting.severity}; ${pickFix(setting.rule)}`,
14
+ }));
15
+ }
16
+
17
+ interface WeakSetting {
18
+ readonly rule: string;
19
+ readonly severity: string;
20
+ readonly line: number;
21
+ }
22
+
23
+ // oxlint reads the rules of the config root and of each override, and no `rules` key deeper, such as
24
+ // one under `settings`
25
+ function collectSettings(root: JSONCNode, isToolsRepo: boolean): WeakSetting[] {
26
+ if (root.kind !== 'object') {
27
+ return [];
28
+ }
29
+
30
+ const overrides = findLastEntry(root.entries, 'overrides')?.value;
31
+ const items = overrides?.kind === 'array' ? overrides.items : [];
32
+
33
+ return [
34
+ ...collectRuleSettings(root.entries, false),
35
+ ...items.flatMap((item) =>
36
+ item.kind === 'object'
37
+ ? collectRuleSettings(item.entries, isToolsRepo && isStdHelperFiles(item.entries))
38
+ : [],
39
+ ),
40
+ ];
41
+ }
42
+
43
+ function collectRuleSettings(
44
+ entries: readonly JSONCEntry[],
45
+ isHelperOverride: boolean,
46
+ ): WeakSetting[] {
47
+ const rules = findLastEntry(entries, 'rules')?.value;
48
+
49
+ return rules?.kind === 'object'
50
+ ? rules.entries.flatMap((rule) => collectWeakSettings(rule, isHelperOverride))
51
+ : [];
52
+ }
53
+
54
+ // oxlint reads a rule under any plugin prefix, such as `@typescript-eslint/ban-ts-comment`, or under
55
+ // its bare name.
56
+ const lockedPattern = /^(?:[^/\s]+\/)?(?:consistent-type-assertions|ban-ts-comment)$/u;
57
+
58
+ const weakSeverities = new Set(['off', 'warn', 'allow', '0', '1']);
59
+
60
+ const helperRule = 'typescript/consistent-type-assertions';
61
+
62
+ function collectWeakSettings(entry: JSONCEntry, isHelperOverride: boolean): WeakSetting[] {
63
+ const isRefused = entry.key.startsWith('zgeoff/') || lockedPattern.test(entry.key);
64
+ const severity = pickSeverity(entry.value);
65
+
66
+ if (!isRefused || severity === null || !weakSeverities.has(severity)) {
67
+ return [];
68
+ }
69
+
70
+ if (isHelperOverride && entry.key === helperRule && isBareOff(entry.value)) {
71
+ return [];
72
+ }
73
+
74
+ return [{ rule: entry.key, severity, line: entry.line }];
75
+ }
76
+
77
+ // the severity is the value, or the first element of an array
78
+ function pickSeverity(value: JSONCNode): string | null {
79
+ const first = value.kind === 'array' ? value.items[0] : value;
80
+
81
+ return first?.kind === 'literal' ? first.text : null;
82
+ }
83
+
84
+ // the lint rule accepts the string alone, and no array that holds it
85
+ function isBareOff(value: JSONCNode): boolean {
86
+ return value.kind === 'literal' && value.text === 'off';
87
+ }
88
+
89
+ function isStdHelperFiles(entries: readonly JSONCEntry[]): boolean {
90
+ const files = findLastEntry(entries, 'files')?.value;
91
+
92
+ return (
93
+ files?.kind === 'array' &&
94
+ files.items.length > 0 &&
95
+ files.items.every((item) => item.kind === 'literal' && stdHelperPaths.includes(item.text))
96
+ );
97
+ }
98
+
99
+ const optionFixes = new Map([
100
+ ['zgeoff/no-abbreviated-names', 'add the key to the `allowedKeys` option of the rule'],
101
+ ['zgeoff/file-named-for-export', 'add the file to the `loaderFiles` option of the rule'],
102
+ ['zgeoff/function-verb', 'add the name to the `exemptNames` option of the rule'],
103
+ ['zgeoff/verb-contract', 'add the name to the `exemptNames` option of the rule'],
104
+ ]);
105
+
106
+ function pickFix(rule: string): string {
107
+ if (lockedPattern.test(rule)) {
108
+ return 'fix the types with a type guard, an annotation, `satisfies`, a schema parse or a `@zgeoff/std` helper, and set no override';
109
+ }
110
+
111
+ const optionFix = optionFixes.get(rule);
112
+
113
+ if (optionFix !== undefined) {
114
+ return `fix the code, or ${optionFix}; delete the setting`;
115
+ }
116
+
117
+ return rule === 'zgeoff/max-test-timeout'
118
+ ? "find the slow test's cause, then rewrite or split it to finish within its lane's limit; delete the setting"
119
+ : 'fix the code and delete the setting: no override exempts this rule';
120
+ }