@ref0/workspace 0.8.0 → 0.10.0

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
@@ -41,8 +41,8 @@ Each copied plugin keeps its licence and its `UPSTREAM.md`, which records its so
41
41
  changes, beside its code, in the package too.
42
42
 
43
43
  `ref0-generic`'s rules: `seeded-properties`, `index-barrel-only` and `export-type-side-effects`,
44
- which `base.lint` turns on, and `effect-encoding`, `log-messages`, `env-at-entrypoints` and
45
- `entry-reexports`, which a repo turns on for its own files. `entry-reexports` takes the repo's root,
44
+ which `base.lint` turns on, and `effect-encoding`, `log-messages`, `env-at-entrypoints`,
45
+ `entry-reexports` and `no-comments`, which a repo turns on for its own files. `entry-reexports` takes the repo's root,
46
46
  the folders of the packages whose entry files it checks, and the export condition that names an
47
47
  entry point's source:
48
48
 
@@ -53,6 +53,25 @@ entry point's source:
53
53
  ],
54
54
  ```
55
55
 
56
+ `no-comments` bans every comment but a doc comment on a declaration, a `SAFETY:` note and a tool's
57
+ directive. Files older than the rule keep the banned comments they had, as a budget that only
58
+ shrinks: a JSON file of each file's path from the root and how many it may hold, which
59
+ `comment-budget` writes. It takes the repo's root and the budget file's path from it, and a repo
60
+ with no budget file yet gives every file none. Turn it on over the repo's files, with an override
61
+ that leaves out what it doesn't own, such as vendored code:
62
+
63
+ ```ts
64
+ {
65
+ files: ['**'],
66
+ excludeFiles: ['vendor/**'],
67
+ rules: {
68
+ 'ref0-generic/no-comments': ['error', { root, budget: 'lint/comment-budget.json' }],
69
+ },
70
+ },
71
+ ```
72
+
73
+ and add `"comments": "ref0-workspace comment-budget"` to the root `package.json`'s scripts.
74
+
56
75
  ## Checks
57
76
 
58
77
  `ref0-workspace <check>`, from anywhere in the repo's checkout:
@@ -62,6 +81,14 @@ entry point's source:
62
81
  Markdown Git tracks. A `SKILL.md` fails past 6 KB and warns past 5 KB, each naming its largest
63
82
  sections to move to `references/`. Upstream copies are the skills the root's `skills-lock.json`
64
83
  names, and each skill with an `.agents/skills/<name>-UPSTREAM.md`.
84
+ - `comment-budget [--write | --grant <path>...]`: each file's banned comments, as
85
+ `ref0-generic/no-comments` counts them, against its budget. It reads the repo's lint config,
86
+ through its own Vite+, for the files the rule runs on and its options, so it needs the rule on
87
+ with one budget. Bare, it names each file over budget, counts what a full sweep would shed, and
88
+ fails when one is over. `--write` lowers each budget to what its file holds, never raising one,
89
+ and drops each file gone or with none left. `--grant <path>...` sets the budget of each file
90
+ under the paths, `.` for all, to what it holds: for a file that moved, the only way a budget
91
+ grows, so a review sees it.
65
92
  - `symbols find <words...>` and `symbols check <base> [<head>]` or `symbols check --all`: what the
66
93
  repo already has, and a change that copies it, as [Symbols](#symbols) says.
67
94
  - `types`: the types of every project the root `tsconfig.json` reaches, and Effect's rules, with
package/dist/bin.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { changelog } from "./changelog.mjs";
3
+ import { commentBudget } from "./comment-budget.mjs";
3
4
  import { commitMessage } from "./commit-message.mjs";
4
5
  import { docsBudget } from "./docs-budget.mjs";
5
6
  import { defaultCondition, packageExports } from "./package-exports.mjs";
@@ -19,6 +20,8 @@ import { parseArgs } from "node:util";
19
20
  * in the repo's checkout.
20
21
  *
21
22
  * ref0-workspace docs-budget the docs agents load, each within its budget
23
+ * ref0-workspace comment-budget [--write | --grant <path>...]
24
+ * each file's banned comments, within its budget
22
25
  * ref0-workspace symbols find <words...> what the repo has, before you write it again
23
26
  * ref0-workspace symbols check <base> [<head>] no change copies what the repo has
24
27
  * ref0-workspace symbols check --all every copy the repo holds
@@ -75,6 +78,11 @@ const checks = /* @__PURE__ */ new Map([
75
78
  console.error(`docs-budget: ${docs.length} Markdown files within budget`);
76
79
  return 0;
77
80
  })],
81
+ ["comment-budget", {
82
+ args: "[--write | --grant <path>...]",
83
+ about: "each file's banned comments, within its budget for ref0-generic/no-comments; --write lowers each budget to what its file holds, and --grant sets the budgets of the files under the paths to what each holds",
84
+ run: (args) => commentBudget(args, root())
85
+ }],
78
86
  ["symbols", {
79
87
  args: "find <words...> | check <base> [<head>] | check --all",
80
88
  about: "what the repo has, before you write it again, and no change copying it",
@@ -1,4 +1,4 @@
1
- import { commitTypes } from "./commit-message.mjs";
1
+ import { commitTypes } from "./subject.mjs";
2
2
  import { execFileSync, spawnSync } from "node:child_process";
3
3
  import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
4
4
  import { execPath, stdout } from "node:process";
@@ -0,0 +1,161 @@
1
+ import { decodeBudget, docTargetsVisitor, kindOf } from "./lint/generic/comments.mjs";
2
+ import { vitePlusAt } from "./types/projects.mjs";
3
+ import { execFile } from "node:child_process";
4
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { execPath } from "node:process";
6
+ import { promisify } from "node:util";
7
+ import { join, matchesGlob, relative, sep } from "node:path";
8
+ import { Schema } from "effect";
9
+ import { Visitor, parseSync } from "vite-plus";
10
+ // src/comment-budget.ts
11
+ /**
12
+ * Counts each file's banned comments, as `ref0-generic/no-comments` sees them, against its budget,
13
+ * and lowers or grants budgets.
14
+ *
15
+ * ref0-workspace comment-budget each file over budget, and what a sweep would shed
16
+ * ref0-workspace comment-budget --write lowers each budget to what the file holds
17
+ * ref0-workspace comment-budget --grant <path>... sets the budget of each file under the paths
18
+ * to what it holds
19
+ *
20
+ * It reads the repo's lint config, through its own Vite+, for the files the rule runs on and its
21
+ * options: the root and the budget file. `--write` never raises a budget, and drops a file that
22
+ * holds none or is gone. `--grant` raises one, for a file that moved, which keeps its comments
23
+ * under a path the budget doesn't know, and is the only way a budget grows, so a review sees it.
24
+ */
25
+ const run = promisify(execFile);
26
+ const rule = "ref0-generic/no-comments";
27
+ /** The rule's options, as a repo's config sets them. */
28
+ const Options = Schema.Struct({
29
+ root: Schema.String,
30
+ budget: Schema.String
31
+ });
32
+ /** A rule's setting as Oxlint prints it: a severity, alone or with its options. */
33
+ const Setting = Schema.Union([Schema.String, Schema.Array(Schema.Unknown)]);
34
+ const Rules = Schema.NullOr(Schema.Record(Schema.String, Setting));
35
+ /** What the command reads of `vp lint --print-config`: the rules, and each override's. */
36
+ const decodePrinted = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Struct({
37
+ rules: Rules,
38
+ overrides: Schema.NullOr(Schema.Array(Schema.Struct({
39
+ files: Schema.Array(Schema.String),
40
+ excludeFiles: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.String))),
41
+ rules: Rules
42
+ })))
43
+ })));
44
+ const decodeOptions = Schema.decodeUnknownSync(Options);
45
+ const isSeverity = Schema.is(Schema.String);
46
+ const off = /* @__PURE__ */ new Set(["off", "allow"]);
47
+ /** The rule's options where `rules` turns it on, `false` where they turn it off, or nothing. */
48
+ const settingIn = (rules) => {
49
+ const setting = rules?.[rule];
50
+ if (setting === void 0) return void 0;
51
+ const [severity, options] = isSeverity(setting) ? [setting] : setting;
52
+ return isSeverity(severity) && off.has(severity) ? false : decodeOptions(options);
53
+ };
54
+ /** A part of a path that starts with a dot, such as `.agents`, with the dot as a letter no glob skips. */
55
+ const shown = (text) => text.replace(/(^|\/)\./gu, "$1");
56
+ /**
57
+ * Whether `glob` takes `path` as an override's does: `*` never crosses a `/`, as `matchesGlob`'s
58
+ * doesn't, but `*` and `**` match a part that starts with a dot, as Oxlint's do and `matchesGlob`'s
59
+ * don't, so `**` reaches `.agents/hooks/`.
60
+ */
61
+ const matches = (path, glob) => matchesGlob(shown(path), shown(glob));
62
+ /**
63
+ * Where the rule runs in the printed config: a file's options, or nothing when it's off there. A
64
+ * later override wins over an earlier one and over the top-level rules, as Oxlint applies them.
65
+ */
66
+ const ruleAt = (printed) => (path) => {
67
+ const setting = (printed.overrides ?? []).reduce((current, { files, excludeFiles, rules }) => files.some((glob) => matches(path, glob)) && !(excludeFiles ?? []).some((glob) => matches(path, glob)) ? settingIn(rules) ?? current : current, settingIn(printed.rules));
68
+ return setting === false ? void 0 : setting;
69
+ };
70
+ /** The banned comments in `text`, the file at `path`, and how many lines they take. */
71
+ const bannedIn = (path, text) => {
72
+ const { program, comments } = parseSync(path, text);
73
+ const targets = /* @__PURE__ */ new Set();
74
+ new Visitor(docTargetsVisitor((start) => targets.add(start))).visit(program);
75
+ const first = program.body[0];
76
+ if (first !== void 0) targets.add(first.start);
77
+ const banned = comments.filter((comment) => comment.type !== "Shebang" && kindOf(comment, text, targets) === "banned");
78
+ const lines = banned.reduce((sum, comment) => sum + text.slice(comment.start, comment.end).split("\n").length, 0);
79
+ return {
80
+ count: banned.length,
81
+ lines
82
+ };
83
+ };
84
+ /** Each budget lowered to what its file holds, dropping each file gone or with none. */
85
+ const lowered = (budget, counts) => Object.fromEntries([...counts].map(([path, count]) => [path, Math.min(count, budget[path] ?? 0)]));
86
+ /** Each file under `prefixes`, `.` for every file, with what it holds as its budget. */
87
+ const granted = (counts, prefixes) => Object.fromEntries([...counts].filter(([path]) => prefixes.some((prefix) => prefix === "." || path === prefix || path.startsWith(`${prefix.replace(/\/$/, "")}/`))));
88
+ /** The budget as its file holds it: sorted by path, each file with none left out. */
89
+ const budgetText = (budget) => `${JSON.stringify(Object.fromEntries(Object.entries(budget).filter(([, count]) => count > 0).sort(([a], [b]) => a < b ? -1 : 1)), null, 2)}\n`;
90
+ /** Runs the repo's own `vp lint` at `root` with `args`, and answers what it prints. */
91
+ const lint = async (root, args) => (await run(execPath, [
92
+ vitePlusAt(root),
93
+ "lint",
94
+ ...args
95
+ ], {
96
+ cwd: root,
97
+ encoding: "utf8",
98
+ maxBuffer: 67108864
99
+ })).stdout;
100
+ /** The command, in the repo at `root`, with its arguments; answers its exit code. */
101
+ const commentBudget = async (args, root) => {
102
+ const [mode, ...paths] = args;
103
+ if (mode !== void 0 && mode !== "--write" && mode !== "--grant") {
104
+ console.error(`comment-budget: unknown flag ${mode}. Run it bare, with --write, or with --grant <path>...`);
105
+ return 2;
106
+ }
107
+ if (mode !== "--grant" && paths.length > 0) {
108
+ console.error(`comment-budget: ${mode ?? "a bare run"} takes no paths.`);
109
+ return 2;
110
+ }
111
+ if (mode === "--grant" && paths.length === 0) {
112
+ console.error("comment-budget: --grant takes the paths whose files keep their comments.");
113
+ return 2;
114
+ }
115
+ const [printed, listed] = await Promise.all([lint(root, ["--print-config"]).then(decodePrinted), lint(root, ["--debug=files"])]);
116
+ const optionsAt = ruleAt(printed);
117
+ const scoped = listed.split("\n").filter((path) => path !== "" && /\.[cm]?[jt]sx?$/.test(path)).flatMap((path) => {
118
+ const options = optionsAt(path);
119
+ return options === void 0 ? [] : [{
120
+ path,
121
+ options
122
+ }];
123
+ });
124
+ const settings = new Set(scoped.map(({ options }) => JSON.stringify(options)));
125
+ const options = scoped[0]?.options;
126
+ if (options === void 0 || settings.size !== 1) {
127
+ console.error(settings.size === 0 ? `comment-budget: lint runs ${rule} on no file. Turn it on in vite.config.ts, with the repo's root and its budget file.` : `comment-budget: ${rule} runs with ${settings.size} sets of options, and the command reads one budget.`);
128
+ return 2;
129
+ }
130
+ const budgetFile = join(options.root, options.budget);
131
+ const budget = existsSync(budgetFile) ? decodeBudget(readFileSync(budgetFile, "utf8")) : {};
132
+ const found = new Map(scoped.map(({ path }) => [relative(options.root, join(root, path)).split(sep).join("/"), bannedIn(path, readFileSync(join(root, path), "utf8"))]));
133
+ const counts = new Map([...found].map(([path, { count }]) => [path, count]));
134
+ if (mode === "--write") {
135
+ writeFileSync(budgetFile, budgetText(lowered(budget, counts)));
136
+ return 0;
137
+ }
138
+ if (mode === "--grant") {
139
+ const grants = granted(counts, paths);
140
+ writeFileSync(budgetFile, budgetText({
141
+ ...budget,
142
+ ...grants
143
+ }));
144
+ console.log(`comment-budget: granted ${Object.values(grants).filter((count) => count > 0).length} files their comments.`);
145
+ return 0;
146
+ }
147
+ const over = [...counts].filter(([path, count]) => count > (budget[path] ?? 0));
148
+ const loose = [...counts].filter(([path, count]) => count < (budget[path] ?? 0));
149
+ const totals = [...found.values()].reduce((sum, { count, lines }) => ({
150
+ count: sum.count + count,
151
+ lines: sum.lines + lines
152
+ }), {
153
+ count: 0,
154
+ lines: 0
155
+ });
156
+ for (const [path, count] of over) console.log(`over ${path}: ${count} of ${budget[path] ?? 0}`);
157
+ console.log(`comment-budget: ${totals.count} banned comments in ${[...counts.values()].filter((count) => count > 0).length} files, ${totals.lines} lines a full sweep would shed.`);
158
+ if (loose.length > 0) console.log(`comment-budget: ${loose.length} budgets are above what their files hold: run --write to lower them.`);
159
+ return over.length > 0 ? 1 : 0;
160
+ };
161
+ export { bannedIn, budgetText, commentBudget, granted, lowered, matches, ruleAt };
@@ -1,3 +1,4 @@
1
+ import { commitTypes, isScopeName, subjectProblem } from "./subject.mjs";
1
2
  import { readFileSync } from "node:fs";
2
3
  import { join } from "node:path";
3
4
  import { Option, Schema } from "effect";
@@ -13,66 +14,13 @@ import { Option, Schema } from "effect";
13
14
  * says. Each repo names its own scopes in its root `package.json`, under `ref0-workspace`, as
14
15
  * `{ "commitScopes": ["git", "cli"] }`, and its `.agents/repo/commits.md` says what each names.
15
16
  *
16
- * A commit may also carry one of git's own subjects: a merge's, `Merge branch …`,
17
- * `Merge remote-tracking branch …`, `Merge commit '…'` or `Merge tag '…'`, or the plural git writes
18
- * for an octopus merge, such as `Merge branches 'a' and 'b'`, an autosquash's,
19
- * `fixup! …`, `squash! …` or `amend! …`, and a revert's, `Revert "…"` or `Reapply "…"`, which
20
- * `git revert` writes without running `commit-msg`. A title may not, since it becomes main's
21
- * subject.
17
+ * The rule for one line is `subject.ts`'s, which needs nothing installed. A commit may also carry
18
+ * one of git's own subjects: a merge's, `Merge branch …`, `Merge remote-tracking branch …`,
19
+ * `Merge commit '…'` or `Merge tag '…'`, or the plural git writes for an octopus merge, such as
20
+ * `Merge branches 'a' and 'b'`, an autosquash's, `fixup! …`, `squash! …` or `amend! …`, and a
21
+ * revert's, `Revert "…"` or `Reapply "…"`, which `git revert` writes without running `commit-msg`.
22
+ * A title may not, since it becomes main's subject.
22
23
  */
23
- /** The kinds of change, in the order the release notes list them. */
24
- const commitTypes = [
25
- "feat",
26
- "fix",
27
- "perf",
28
- "refactor",
29
- "test",
30
- "docs",
31
- "build",
32
- "ci",
33
- "chore",
34
- "revert"
35
- ];
36
- /**
37
- * git's own subjects, which a commit may carry and a title may not: a merge's, as `fmt-merge-msg`
38
- * writes it for one or several of a kind, an autosquash's and a revert's.
39
- */
40
- const gitsOwn = /^(?:Merge (?:branch(?:es)? |remote-tracking branch(?:es)? |commits? '|tags? ')|(?:fixup|squash|amend)! |(?:Revert|Reapply) ")/u;
41
- /** `type`, then `(scope)` or nothing, then `!` or nothing, then `: ` and the words. */
42
- const subjectLine = /^([^\s(!:]+)(?:\(([^()]*)\))?!?: (\S(?:.*\S)?)$/u;
43
- /** A scope's name, as a repo may give it: lower case words joined by `-`. */
44
- const scopeName = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
45
- const read = (line, scopes) => {
46
- const match = subjectLine.exec(line);
47
- if (match === null) return {
48
- valid: false,
49
- problem: `"${line}" isn't "type(scope): subject", or "type: subject" for a change across the repo`
50
- };
51
- const [, word = "", named, text = ""] = match;
52
- const type = commitTypes.find((each) => each === word);
53
- if (type === void 0) return {
54
- valid: false,
55
- problem: `"${word}" isn't a type: use one of ${commitTypes.join(", ")}`
56
- };
57
- if (named !== void 0 && !scopes.includes(named)) return {
58
- valid: false,
59
- problem: `"${named}" isn't a scope: ${scopes.length === 0 ? "this repo names none, so leave it off" : `use one of ${scopes.join(", ")}, or none`}`
60
- };
61
- return {
62
- valid: true,
63
- subject: {
64
- type,
65
- scope: named,
66
- text
67
- }
68
- };
69
- };
70
- /** What's wrong with `line` as a commit's subject or a pull request's title, or undefined. */
71
- const subjectProblem = (line, checked, scopes) => {
72
- if (checked === "commit" && gitsOwn.test(line)) return void 0;
73
- const subject = read(line, scopes);
74
- return subject.valid ? void 0 : subject.problem;
75
- };
76
24
  /**
77
25
  * A comment as git's editor and a commit template write one: `#` alone, or `#` and a space. `-m`
78
26
  * keeps every line, so a line such as `#123: a fix` is a subject, never a comment. In the editor,
@@ -113,7 +61,7 @@ const commitScopes = (root) => {
113
61
  const manifest = decodeManifest(text);
114
62
  if (Option.isNone(manifest)) return { problem: `${where} isn't a list of words: name the repo's scopes, or [] for none` };
115
63
  const scopes = manifest.value["ref0-workspace"].commitScopes;
116
- const wrong = scopes.find((scope) => !scopeName.test(scope));
64
+ const wrong = scopes.find((scope) => !isScopeName(scope));
117
65
  if (wrong !== void 0) return { problem: `${where} holds ${JSON.stringify(wrong)}: a scope is lower case words joined by -` };
118
66
  return { scopes };
119
67
  };
@@ -135,4 +83,4 @@ const commitMessage = (args, root) => {
135
83
  console.error(`${title ? "The pull request's title" : "The commit's subject"}: ${problem}. .agents/repo/commits.md says how.`);
136
84
  return 1;
137
85
  };
138
- export { commitMessage, commitScopes, commitTypes, messageProblem, messageSubject, subjectProblem };
86
+ export { commitMessage, commitScopes, commitTypes, messageProblem, messageSubject };
@@ -0,0 +1,53 @@
1
+ import { Schema } from "effect";
2
+ // src/lint/generic/comments.ts
3
+ /** A comment a tool reads: a lint or type-check switch, a test environment, or a bundler hint. */
4
+ const directive = /^\s*(?:(?:eslint|oxlint)(?:-disable|-enable|-env)?\b|@ts-(?:expect-error|ignore|nocheck|check)\b|@effect-diagnostics|@vitest-environment|@vite-ignore|@jsx|prettier-ignore|oxfmt-ignore|biome-ignore|(?:c8|v8|istanbul) ignore|webpack[A-Z]|[#@]__[A-Z_]+__|\/\s*<reference\b)/;
5
+ /** The anti-slop rule's own test for a justification, with its default marker. */
6
+ const safety = /(?:^|[^\p{L}\p{N}_])SAFETY\s*:\s*\S/u;
7
+ /**
8
+ * Each node a doc comment may sit on: a declaration, an export, a class or interface member, an
9
+ * enum member and an object's property. A comment just before one documents it to editors and
10
+ * agents, which read it on hover and in declaration files.
11
+ */
12
+ const documented = [
13
+ "AccessorProperty",
14
+ "ClassDeclaration",
15
+ "ExportDefaultDeclaration",
16
+ "ExportNamedDeclaration",
17
+ "FunctionDeclaration",
18
+ "MethodDefinition",
19
+ "Property",
20
+ "PropertyDefinition",
21
+ "TSAbstractAccessorProperty",
22
+ "TSAbstractMethodDefinition",
23
+ "TSAbstractPropertyDefinition",
24
+ "TSCallSignatureDeclaration",
25
+ "TSConstructSignatureDeclaration",
26
+ "TSDeclareFunction",
27
+ "TSEnumDeclaration",
28
+ "TSEnumMember",
29
+ "TSIndexSignature",
30
+ "TSInterfaceDeclaration",
31
+ "TSMethodSignature",
32
+ "TSModuleDeclaration",
33
+ "TSPropertySignature",
34
+ "TSTypeAliasDeclaration",
35
+ "VariableDeclaration"
36
+ ];
37
+ /**
38
+ * A visitor that hands `add` where each node a doc comment may sit on starts. It visits Oxlint's
39
+ * tree in a rule and oxc's from `parseSync`, so each node is only its start. The caller adds where
40
+ * the file's first statement starts, whose doc comment is the module's.
41
+ */
42
+ const docTargetsVisitor = (add) => Object.fromEntries(documented.map((type) => [type, (node) => add(node.start)]));
43
+ /** What `comment` is in `text`, given where each node a doc comment may sit on starts. */
44
+ const kindOf = (comment, text, targets) => {
45
+ if (comment.type === "Shebang" || directive.test(comment.value)) return "directive";
46
+ if (safety.test(comment.value)) return "safety";
47
+ if (comment.type !== "Block" || !comment.value.startsWith("*")) return "banned";
48
+ const next = text.slice(comment.end).search(/\S/);
49
+ return next !== -1 && targets.has(comment.end + next) ? "doc" : "banned";
50
+ };
51
+ /** Each file's budget of banned comments, by its path from the repo's root, as its budget file holds it. */
52
+ const decodeBudget = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Record(Schema.String, Schema.Number)));
53
+ export { decodeBudget, docTargetsVisitor, kindOf };
@@ -0,0 +1,79 @@
1
+ import { decodeBudget, docTargetsVisitor, kindOf } from "./comments.mjs";
2
+ import { existsSync, readFileSync, statSync } from "node:fs";
3
+ import { join, relative, resolve, sep } from "node:path";
4
+ import { Schema } from "effect";
5
+ import { defineRule } from "vite-plus/lint/plugins";
6
+ // src/lint/generic/no-comments.ts
7
+ /**
8
+ * What the rule takes: the repo's root, as an absolute path, and `budget`, the budget file's path
9
+ * from it, such as `lint/comment-budget.json`, which `ref0-workspace comment-budget` writes.
10
+ */
11
+ const decodeOptions = Schema.decodeUnknownSync(Schema.Tuple([Schema.Struct({
12
+ root: Schema.String,
13
+ budget: Schema.String
14
+ })]));
15
+ /** Each budget file as last read, by its absolute path, with its modified time then. */
16
+ const budgets = /* @__PURE__ */ new Map();
17
+ /**
18
+ * The budget file at `path`, read again only when it has changed, as an editor's lint runs on. A
19
+ * repo with none yet gives every file a budget of none.
20
+ */
21
+ const budgetAt = (path) => {
22
+ if (!existsSync(path)) return {};
23
+ const at = statSync(path).mtimeMs;
24
+ const kept = budgets.get(path);
25
+ if (kept?.at === at) return kept.budget;
26
+ const budget = decodeBudget(readFileSync(path, "utf8"));
27
+ budgets.set(path, {
28
+ at,
29
+ budget
30
+ });
31
+ return budget;
32
+ };
33
+ /**
34
+ * Code says what it does, and a comment beside it goes stale, excuses a hack or repeats it. A file
35
+ * holds none, but for a tool's directive, a `SAFETY:` note on a type assertion, and a doc comment
36
+ * on a declaration, which says why it is as it is. Files older than the rule keep the banned
37
+ * comments they had, as a budget that only shrinks: `ref0-workspace comment-budget --write` lowers
38
+ * each file's to what's left.
39
+ */
40
+ const noCommentsRule = defineRule({
41
+ meta: {
42
+ messages: { overBudget: "This file holds {{count}} comments that are neither a doc comment on a declaration, a `SAFETY:` note nor a directive, and its budget is {{budget}}. Make the code say it, or put the reason in the doc comment of the declaration it explains." },
43
+ schema: [{
44
+ type: "object",
45
+ properties: {
46
+ root: { type: "string" },
47
+ budget: { type: "string" }
48
+ },
49
+ required: ["root", "budget"],
50
+ additionalProperties: false
51
+ }]
52
+ },
53
+ create(context) {
54
+ const [{ root, budget: budgetPath }] = decodeOptions(context.options);
55
+ const path = relative(root, resolve(context.filename)).split(sep).join("/");
56
+ const budget = budgetAt(join(root, budgetPath))[path] ?? 0;
57
+ const targets = /* @__PURE__ */ new Set();
58
+ return {
59
+ ...docTargetsVisitor((start) => targets.add(start)),
60
+ "Program:exit"() {
61
+ const text = context.sourceCode.text;
62
+ const firstStatement = context.sourceCode.ast.body[0];
63
+ if (firstStatement !== void 0) targets.add(firstStatement.start);
64
+ const banned = context.sourceCode.getAllComments().filter((comment) => kindOf(comment, text, targets) === "banned");
65
+ const firstOver = banned[budget];
66
+ if (firstOver === void 0) return;
67
+ context.report({
68
+ loc: context.sourceCode.getLoc(firstOver),
69
+ messageId: "overBudget",
70
+ data: {
71
+ count: String(banned.length),
72
+ budget: String(budget)
73
+ }
74
+ });
75
+ }
76
+ };
77
+ }
78
+ });
79
+ export { noCommentsRule };
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Rules any ref-0 repo can turn on, each over the files its config names. Only `entry-reexports`
3
- * takes options: the repo's root, its packages and its source condition.
2
+ * Rules any ref-0 repo can turn on, each over the files its config names. Two take options:
3
+ * `entry-reexports` the repo's root, its packages and its source condition, and `no-comments` the
4
+ * repo's root and its comment budget's file.
4
5
  */
5
6
  declare const _default: import("vite-plus/lint/plugins").Plugin;
6
7
  export { _default as default };
@@ -4,12 +4,14 @@ import { envAtEntrypointsRule } from "./env-at-entrypoints.mjs";
4
4
  import { exportTypeSideEffectsRule } from "./export-type-side-effects.mjs";
5
5
  import { indexBarrelOnlyRule } from "./index-barrel.mjs";
6
6
  import { logMessagesRule } from "./log-messages.mjs";
7
+ import { noCommentsRule } from "./no-comments.mjs";
7
8
  import { seededPropertiesRule } from "./seeded-properties.mjs";
8
9
  import { definePlugin } from "vite-plus/lint/plugins";
9
10
  // src/lint/generic/plugin.ts
10
11
  /**
11
- * Rules any ref-0 repo can turn on, each over the files its config names. Only `entry-reexports`
12
- * takes options: the repo's root, its packages and its source condition.
12
+ * Rules any ref-0 repo can turn on, each over the files its config names. Two take options:
13
+ * `entry-reexports` the repo's root, its packages and its source condition, and `no-comments` the
14
+ * repo's root and its comment budget's file.
13
15
  */
14
16
  var plugin_default = definePlugin({
15
17
  meta: { name: "ref0-generic" },
@@ -20,6 +22,7 @@ var plugin_default = definePlugin({
20
22
  "export-type-side-effects": exportTypeSideEffectsRule,
21
23
  "index-barrel-only": indexBarrelOnlyRule,
22
24
  "log-messages": logMessagesRule,
25
+ "no-comments": noCommentsRule,
23
26
  "seeded-properties": seededPropertiesRule
24
27
  }
25
28
  });
@@ -0,0 +1,63 @@
1
+ // src/subject.ts
2
+ /**
3
+ * The commit format's rule for one line, `type(scope): subject`, with nothing but the language:
4
+ * no `effect` and no file reads. `commit-message.ts` reads a message and a repo's scopes around it,
5
+ * and `scripts/save-subject.ts` runs it with Node's own type stripping, from `home.sh save` and
6
+ * `wiki.sh save`, where no `node_modules` may be installed.
7
+ */
8
+ /** The kinds of change, in the order the release notes list them. */
9
+ const commitTypes = [
10
+ "feat",
11
+ "fix",
12
+ "perf",
13
+ "refactor",
14
+ "test",
15
+ "docs",
16
+ "build",
17
+ "ci",
18
+ "chore",
19
+ "revert"
20
+ ];
21
+ /**
22
+ * git's own subjects, which a commit may carry and a title may not: a merge's, as `fmt-merge-msg`
23
+ * writes it for one or several of a kind, an autosquash's and a revert's.
24
+ */
25
+ const gitsOwn = /^(?:Merge (?:branch(?:es)? |remote-tracking branch(?:es)? |commits? '|tags? ')|(?:fixup|squash|amend)! |(?:Revert|Reapply) ")/u;
26
+ /** `type`, then `(scope)` or nothing, then `!` or nothing, then `: ` and the words. */
27
+ const subjectLine = /^([^\s(!:]+)(?:\(([^()]*)\))?!?: (\S(?:.*\S)?)$/u;
28
+ /** A scope's name, as a repo may give it: lower case words joined by `-`. */
29
+ const scopeName = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
30
+ /** Whether `scope` is a name a repo may give a scope: lower case words joined by `-`. */
31
+ const isScopeName = (scope) => scopeName.test(scope);
32
+ const read = (line, scopes) => {
33
+ const match = subjectLine.exec(line);
34
+ if (match === null) return {
35
+ valid: false,
36
+ problem: `"${line}" isn't "type(scope): subject", or "type: subject" for a change across the repo`
37
+ };
38
+ const [, word = "", named, text = ""] = match;
39
+ const type = commitTypes.find((each) => each === word);
40
+ if (type === void 0) return {
41
+ valid: false,
42
+ problem: `"${word}" isn't a type: use one of ${commitTypes.join(", ")}`
43
+ };
44
+ if (named !== void 0 && !scopes.includes(named)) return {
45
+ valid: false,
46
+ problem: `"${named}" isn't a scope: ${scopes.length === 0 ? "this repo names none, so leave it off" : `use one of ${scopes.join(", ")}, or none`}`
47
+ };
48
+ return {
49
+ valid: true,
50
+ subject: {
51
+ type,
52
+ scope: named,
53
+ text
54
+ }
55
+ };
56
+ };
57
+ /** What's wrong with `line` as a commit's subject or a pull request's title, or undefined. */
58
+ const subjectProblem = (line, checked, scopes) => {
59
+ if (checked === "commit" && gitsOwn.test(line)) return void 0;
60
+ const subject = read(line, scopes);
61
+ return subject.valid ? void 0 : subject.problem;
62
+ };
63
+ export { commitTypes, isScopeName, subjectProblem };
@@ -3,9 +3,9 @@ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "
3
3
  import { pid } from "node:process";
4
4
  import { dirname, join } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
+ import { parseAst } from "vite-plus";
6
7
  import { createHash } from "node:crypto";
7
8
  import { deserialize, serialize } from "node:v8";
8
- import { parseAst } from "vite-plus";
9
9
  // src/symbols/symbols.ts
10
10
  /**
11
11
  * The functions, classes, consts and types declared at the top level of the repo's source files,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ref0/workspace",
3
- "version": "0.8.0",
3
+ "version": "0.10.0",
4
4
  "description": "The lint and workspace checks every ref-0 repo shares",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -34,21 +34,21 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
- "effect": "4.1.4",
37
+ "effect": "4.1.7",
38
38
  "git-cliff": "2.14.2"
39
39
  },
40
40
  "devDependencies": {
41
- "@effect/tsgo": "0.70.0",
42
- "@types/node": "24.19.2",
43
- "tsrs": "7.1.0-beta.tsrs2",
41
+ "@effect/tsgo": "0.74.0",
42
+ "@types/node": "24.19.4",
43
+ "tsrs": "7.1.0-beta.tsrs4",
44
44
  "typescript": "7.0.2",
45
- "vite-plus": "1.7.0"
45
+ "vite-plus": "1.8.0"
46
46
  },
47
47
  "peerDependencies": {
48
- "@effect/tsgo": "0.70.0",
49
- "tsrs": "7.1.0-beta.tsrs2",
48
+ "@effect/tsgo": "0.74.0",
49
+ "tsrs": "7.1.0-beta.tsrs4",
50
50
  "typescript": "7.0.2",
51
- "vite-plus": "1.7.0"
51
+ "vite-plus": "1.8.0"
52
52
  },
53
53
  "peerDependenciesMeta": {
54
54
  "@effect/tsgo": {