@siim-m/config 0.2.0 → 0.4.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.
@@ -0,0 +1,336 @@
1
+ /** Resolve an identifier node to its binding by walking lexical scopes upward. */
2
+ export function resolveIdentifier(sourceCode, identifier) {
3
+ let scope = sourceCode.getScope(identifier);
4
+ while (scope !== null) {
5
+ const variable = scope.set.get(identifier.name);
6
+ if (variable !== undefined)
7
+ return variable;
8
+ scope = scope.upper;
9
+ }
10
+ return null;
11
+ }
12
+ const effectModules = new Set([
13
+ "Context",
14
+ "Effect",
15
+ "HttpClient",
16
+ "Layer",
17
+ "ManagedRuntime",
18
+ "Schedule",
19
+ "Stream",
20
+ ]);
21
+ /** Barrels that re-export Effect modules as named exports. */
22
+ const moduleBarrels = new Set(["effect", "effect/http"]);
23
+ /** The module a namespace import of `source` binds: `effect/Schedule` or `effect/http/HttpClient`. */
24
+ function namespaceModule(source) {
25
+ if (source.startsWith("effect/http/"))
26
+ return source.slice("effect/http/".length);
27
+ return source.startsWith("effect/") ? source.slice("effect/".length) : "";
28
+ }
29
+ const isEffectModule = (name) => effectModules.has(name);
30
+ const importedName = (specifier) => specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
31
+ /**
32
+ * Collect `import { Effect } from "effect"`, `import { HttpClient } from "effect/http"`,
33
+ * `import * as Effect from "effect/Effect"`, and `import * as HttpClient from "effect/http/HttpClient"` bindings.
34
+ */
35
+ export function collectEffectModuleNames(program) {
36
+ const names = new Map();
37
+ const add = (module, local) => {
38
+ const existing = names.get(module) ?? new Set();
39
+ existing.add(local);
40
+ names.set(module, existing);
41
+ };
42
+ for (const statement of program.body) {
43
+ if (statement.type !== "ImportDeclaration")
44
+ continue;
45
+ const source = statement.source.value;
46
+ if (moduleBarrels.has(source)) {
47
+ for (const specifier of statement.specifiers) {
48
+ if (specifier.type !== "ImportSpecifier")
49
+ continue;
50
+ const name = importedName(specifier);
51
+ if (isEffectModule(name))
52
+ add(name, specifier.local.name);
53
+ }
54
+ continue;
55
+ }
56
+ const module = namespaceModule(source);
57
+ if (!isEffectModule(module))
58
+ continue;
59
+ for (const specifier of statement.specifiers) {
60
+ if (specifier.type === "ImportNamespaceSpecifier" || specifier.type === "ImportDefaultSpecifier") {
61
+ add(module, specifier.local.name);
62
+ }
63
+ }
64
+ }
65
+ return names;
66
+ }
67
+ /** Strip parentheses, type assertions and instantiation expressions from an expression. */
68
+ export function unwrapExpression(expression) {
69
+ let current = expression;
70
+ while (current.type === "ParenthesizedExpression" ||
71
+ current.type === "TSAsExpression" ||
72
+ current.type === "TSSatisfiesExpression" ||
73
+ current.type === "TSTypeAssertion" ||
74
+ current.type === "TSNonNullExpression" ||
75
+ current.type === "TSInstantiationExpression") {
76
+ current = current.expression;
77
+ }
78
+ return current;
79
+ }
80
+ /** Like {@link unwrapExpression}, for any node. */
81
+ export function unwrapNode(node) {
82
+ let current = node;
83
+ while (current.type === "ParenthesizedExpression" ||
84
+ current.type === "TSAsExpression" ||
85
+ current.type === "TSSatisfiesExpression" ||
86
+ current.type === "TSTypeAssertion" ||
87
+ current.type === "TSNonNullExpression" ||
88
+ current.type === "TSInstantiationExpression") {
89
+ current = current.expression;
90
+ }
91
+ return current;
92
+ }
93
+ /** The member name when `node` is `<module>.<member>` for one of the module's local names, else null. */
94
+ export function moduleMemberName(node, names, module) {
95
+ if (node === null || node === undefined)
96
+ return null;
97
+ const expression = node.type === "TSInstantiationExpression" ? node.expression : node;
98
+ if (expression.type !== "MemberExpression" ||
99
+ expression.computed ||
100
+ expression.object.type !== "Identifier" ||
101
+ !(names.get(module)?.has(expression.object.name) ?? false) ||
102
+ expression.property.type !== "Identifier") {
103
+ return null;
104
+ }
105
+ return expression.property.name;
106
+ }
107
+ /** The member name when `node` is a call of `<module>.<member>(...)`, else null. */
108
+ export function moduleCallName(node, names, module) {
109
+ return node?.type === "CallExpression" ? moduleMemberName(unwrapExpression(node.callee), names, module) : null;
110
+ }
111
+ /** Read a Context.Service class declaration, or null when the class is not one. */
112
+ export function serviceClass(node, names) {
113
+ if (node.superClass === null)
114
+ return null;
115
+ const superClass = unwrapExpression(node.superClass);
116
+ if (superClass.type !== "CallExpression")
117
+ return null;
118
+ const factory = unwrapExpression(superClass.callee);
119
+ if (factory.type !== "CallExpression" || moduleMemberName(unwrapExpression(factory.callee), names, "Context") !== "Service") {
120
+ return null;
121
+ }
122
+ const optionsArgument = superClass.arguments[1];
123
+ const options = optionsArgument !== undefined && optionsArgument.type !== "SpreadElement"
124
+ ? unwrapExpression(optionsArgument)
125
+ : null;
126
+ return {
127
+ node,
128
+ name: node.id?.name ?? null,
129
+ options: options?.type === "ObjectExpression" ? options : null,
130
+ };
131
+ }
132
+ /** The innermost class whose body contains `node`, or null. */
133
+ export function enclosingClass(node) {
134
+ let current = node.parent;
135
+ while (current !== null) {
136
+ if (current.type === "ClassBody")
137
+ return current.parent.type === "ClassDeclaration" || current.parent.type === "ClassExpression" ? current.parent : null;
138
+ current = current.parent;
139
+ }
140
+ return null;
141
+ }
142
+ /** Whether `node` names the service class: `this` inside its static members, or its class name. */
143
+ function isClassReference(node, service) {
144
+ if (node === null || node === undefined)
145
+ return false;
146
+ const expression = unwrapNode(node);
147
+ if (expression.type === "ThisExpression")
148
+ return true;
149
+ return expression.type === "Identifier" && service.name !== null && expression.name === service.name;
150
+ }
151
+ /** The member name when `node` is `this.<member>` or `<ClassName>.<member>`, else null. */
152
+ export function classMemberName(node, service) {
153
+ if (node === null || node === undefined)
154
+ return null;
155
+ const expression = unwrapNode(node);
156
+ if (expression.type !== "MemberExpression" ||
157
+ expression.computed ||
158
+ expression.property.type !== "Identifier" ||
159
+ !isClassReference(expression.object, service)) {
160
+ return null;
161
+ }
162
+ return expression.property.name;
163
+ }
164
+ /** The name of a non-computed property key, or null. */
165
+ export function keyName(key) {
166
+ if (key.type === "Identifier" || key.type === "PrivateIdentifier")
167
+ return key.name;
168
+ if (key.type === "Literal" && typeof key.value === "string")
169
+ return key.value;
170
+ return null;
171
+ }
172
+ /** The `name` property of an object expression, or null. */
173
+ function objectProperty(object, name) {
174
+ for (const property of object.properties) {
175
+ if (property.type === "Property" && !property.computed && keyName(property.key) === name)
176
+ return property;
177
+ }
178
+ return null;
179
+ }
180
+ /** Every non-computed static member of a class. */
181
+ export function staticMembers(node) {
182
+ const members = [];
183
+ for (const element of node.body.body) {
184
+ if ((element.type !== "PropertyDefinition" && element.type !== "MethodDefinition") || !element.static || element.computed)
185
+ continue;
186
+ const name = keyName(element.key);
187
+ if (name === null)
188
+ continue;
189
+ members.push({ name, node: element, value: element.value });
190
+ }
191
+ return members;
192
+ }
193
+ /** The expressions that construct the service: the options `make` and a static `make`. */
194
+ export function serviceMakes(service) {
195
+ const makes = [];
196
+ const optionsMake = service.options === null ? null : objectProperty(service.options, "make");
197
+ if (optionsMake !== null)
198
+ makes.push(optionsMake.value);
199
+ for (const member of staticMembers(service.node)) {
200
+ if (member.name === "make" && member.value !== null)
201
+ makes.push(member.value);
202
+ }
203
+ return makes;
204
+ }
205
+ const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
206
+ /** Whether the file is a `*.test.*` or `*.spec.*` file. */
207
+ export const isTestFile = (filename) => TEST_FILE.test(filename.replaceAll("\\", "/"));
208
+ const skippedKeys = new Set(["parent", "loc", "range", "start", "end"]);
209
+ const isNode = (value) => typeof value === "object" && value !== null && "type" in value && typeof value.type === "string";
210
+ /** Visit every descendant of `node`. Return false from `visit` to skip a node's children. */
211
+ export function walk(node, visit) {
212
+ if (!visit(node))
213
+ return;
214
+ for (const [key, value] of Object.entries(node)) {
215
+ if (skippedKeys.has(key))
216
+ continue;
217
+ if (Array.isArray(value)) {
218
+ for (const item of value) {
219
+ if (isNode(item))
220
+ walk(item, visit);
221
+ }
222
+ }
223
+ else if (isNode(value)) {
224
+ walk(value, visit);
225
+ }
226
+ }
227
+ }
228
+ /** Whether any descendant of `node`, including itself, satisfies `predicate`. */
229
+ export function contains(node, predicate) {
230
+ let found = false;
231
+ walk(node, (current) => {
232
+ if (found)
233
+ return false;
234
+ if (predicate(current))
235
+ found = true;
236
+ return !found;
237
+ });
238
+ return found;
239
+ }
240
+ /** Whether `node` is a function expression, arrow, or declaration. */
241
+ export const isFunction = (node) => node?.type === "ArrowFunctionExpression" ||
242
+ node?.type === "FunctionExpression" ||
243
+ node?.type === "FunctionDeclaration";
244
+ /** The return statements of a function body, without descending into nested functions. */
245
+ export function ownReturns(body) {
246
+ const returns = [];
247
+ walk(body, (node) => {
248
+ if (node !== body && isFunction(node))
249
+ return false;
250
+ if (node.type === "ReturnStatement")
251
+ returns.push(node);
252
+ return true;
253
+ });
254
+ return returns;
255
+ }
256
+ /** The expressions a function produces: its expression body or the arguments of its own returns. */
257
+ export function returnedExpressions(fn) {
258
+ if (fn.body === null)
259
+ return [];
260
+ if (fn.body.type !== "BlockStatement")
261
+ return [fn.body];
262
+ return ownReturns(fn.body).flatMap((statement) => (statement.argument === null ? [] : [statement.argument]));
263
+ }
264
+ const isPipeMember = (node) => node.type === "MemberExpression" &&
265
+ !node.computed &&
266
+ node.property.type === "Identifier" &&
267
+ node.property.name === "pipe";
268
+ /** For `x.pipe(...)`, the receiver `x`; otherwise null. */
269
+ export function pipeReceiver(node) {
270
+ if (node.type !== "CallExpression")
271
+ return null;
272
+ const callee = unwrapExpression(node.callee);
273
+ return isPipeMember(callee) ? unwrapExpression(callee.object) : null;
274
+ }
275
+ /**
276
+ * The steps that run before `call` when it is an argument of a pipeline-like call such as `x.pipe(a, call)`,
277
+ * `pipe(x, a, call)`, or `Effect.fn("name")(body, a, call)`, including earlier `.pipe(...)` receivers.
278
+ */
279
+ export function precedingSteps(call) {
280
+ const parent = call.parent;
281
+ if (parent?.type !== "CallExpression")
282
+ return [];
283
+ const index = parent.arguments.findIndex((argument) => argument === call);
284
+ if (index < 0)
285
+ return [];
286
+ const steps = [];
287
+ let receiver = pipeReceiver(parent);
288
+ while (receiver !== null) {
289
+ steps.push(receiver);
290
+ if (receiver.type === "CallExpression")
291
+ steps.push(...receiver.arguments);
292
+ receiver = pipeReceiver(receiver);
293
+ }
294
+ steps.push(...parent.arguments.slice(0, index));
295
+ return steps;
296
+ }
297
+ /** The initializer of the single declarator an identifier resolves to, or the declared function. */
298
+ export function resolveInitializer(sourceCode, identifier) {
299
+ const variable = resolveIdentifier(sourceCode, identifier);
300
+ if (variable === null || variable.defs.length !== 1)
301
+ return null;
302
+ const [definition] = variable.defs;
303
+ if (definition === undefined)
304
+ return null;
305
+ if (definition.type === "FunctionName" && definition.node.type === "FunctionDeclaration")
306
+ return definition.node;
307
+ if (definition.type !== "Variable" || definition.node.type !== "VariableDeclarator")
308
+ return null;
309
+ return definition.node.init ?? null;
310
+ }
311
+ /** The generator passed to `Effect.gen(...)`, or null when `node` is not such a call. */
312
+ export function genFunction(node, names) {
313
+ if (moduleCallName(node, names, "Effect") !== "gen" || node.type !== "CallExpression")
314
+ return null;
315
+ const body = node.arguments.at(-1);
316
+ return body?.type === "FunctionExpression" ? body : null;
317
+ }
318
+ /**
319
+ * The generator body that builds a service from a make expression: `Effect.gen(function* () {...})`, optionally
320
+ * followed by `.pipe(...)`, or an arrow that returns one.
321
+ */
322
+ export function makeGenerator(make, names) {
323
+ let expression = unwrapExpression(make);
324
+ if (expression.type === "ArrowFunctionExpression" || expression.type === "FunctionExpression") {
325
+ const [returned] = returnedExpressions(expression);
326
+ if (returned === undefined)
327
+ return null;
328
+ expression = unwrapExpression(returned);
329
+ }
330
+ let receiver = pipeReceiver(expression);
331
+ while (receiver !== null) {
332
+ expression = receiver;
333
+ receiver = pipeReceiver(expression);
334
+ }
335
+ return genFunction(expression, names);
336
+ }
@@ -1,4 +1,7 @@
1
1
  import { eslintCompatPlugin } from "@oxlint/plugins";
2
+ import { commentsRule } from "./rules/comments.js";
3
+ import { noDisabledTypeAssertionRulesRule } from "./rules/no-disabled-type-assertion-rules.js";
4
+ import { requireSuppressionReasonRule } from "./rules/require-suppression-reason.js";
2
5
  import { noReduceAccumulatorCopyRule } from "./rules/no-reduce-accumulator-copy.js";
3
6
  import { noChainedTypeAssertionsRule } from "./rules/no-chained-type-assertions.js";
4
7
  import { noConditionalEmptyObjectSpreadRule } from "./rules/no-conditional-empty-object-spread.js";
@@ -20,9 +23,11 @@ import { requireSafetyCommentForTypeAssertionRule } from "./rules/require-safety
20
23
  const antiSlopPlugin = eslintCompatPlugin({
21
24
  meta: { name: "anti-slop" },
22
25
  rules: {
26
+ comments: commentsRule,
23
27
  "no-reduce-accumulator-copy": noReduceAccumulatorCopyRule,
24
28
  "no-chained-type-assertions": noChainedTypeAssertionsRule,
25
29
  "no-conditional-empty-object-spread": noConditionalEmptyObjectSpreadRule,
30
+ "no-disabled-type-assertion-rules": noDisabledTypeAssertionRulesRule,
26
31
  "no-known-value-widening": noKnownValueWideningRule,
27
32
  "no-module-mocking": noModuleMockingRule,
28
33
  "no-object-parameters": noObjectParametersRule,
@@ -36,6 +41,7 @@ const antiSlopPlugin = eslintCompatPlugin({
36
41
  "no-widen-then-assert": noWidenThenAssertRule,
37
42
  "require-pascal-case-namespace-imports": requirePascalCaseNamespaceImportsRule,
38
43
  "require-readable-spacing": requireReadableSpacingRule,
44
+ "require-suppression-reason": requireSuppressionReasonRule,
39
45
  "require-safety-comment-for-type-assertion": requireSafetyCommentForTypeAssertionRule,
40
46
  },
41
47
  });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Keep only comments that carry what the code can't: directives, licence headers, docs on exports,
3
+ * the reason above a suppression and comments that start with an allowed prefix such as `SAFETY:`.
4
+ * Each gets one line, a word limit and no doc that only repeats the name below it.
5
+ */
6
+ export declare const commentsRule: import("@oxlint/plugins").Rule;
@@ -0,0 +1,289 @@
1
+ import { defineRule } from '@oxlint/plugins';
2
+ const DIRECTIVE = /^(?:(?:oxlint|eslint)-(?:disable|enable|env)\b|eslint\s+[\w@/-]+\s*:\s*(?:off|warn|error|[012]|\[)|@ts-(?:expect-error|ignore|nocheck|check)\b|@effect-diagnostics|(?:prettier|oxfmt)-ignore|biome-ignore|svelte-ignore|(?:c8|v8|istanbul)\s+ignore|@(?:vitest|jest)-environment|@vite-ignore|webpack[A-Z]\w*:|@jsx|[@#]__(?:PURE|NO_SIDE_EFFECTS|INLINE|NOINLINE)__|\/\s*<(?:reference|amd-module|amd-dependency)\s|#\s*source(?:Mapping)?URL=|#(?:end)?region\b|nosemgrep\b)/u;
3
+ const LICENSE = /@license\b|\bSPDX-License-Identifier\b/u;
4
+ const COPYRIGHT = /\bcopyright\b/iu;
5
+ const SUPPRESSION = /^\s*\*?\s*(?:(?:oxlint|eslint)-disable|@ts-(?:expect-error|ignore|nocheck))/u;
6
+ const FILLER = new Set('a an the of for to in on at by with from and or is are be this that it its as'.split(' '));
7
+ /** The words a comment or name carries once filler words go and plurals fold. */
8
+ const contentWords = (text) => (text.toLowerCase().match(/[a-z0-9]+/gu) ?? [])
9
+ .filter((word) => !FILLER.has(word))
10
+ .map((word) => (word.length > 3 ? word.replace(/([^s])s$/u, '$1') : word))
11
+ .filter((word) => !FILLER.has(word));
12
+ const nameWords = (name) => new Set(contentWords(name.replace(/([a-z0-9])([A-Z])/gu, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/gu, '$1 $2')));
13
+ /** Whether a doc says nothing but the words of the name it documents. */
14
+ function restatesName(lines, name) {
15
+ if (lines.some((line) => line.startsWith('@')))
16
+ return false;
17
+ const words = contentWords(lines.join(' '));
18
+ const fromName = nameWords(name);
19
+ return words.length > 0 && words.length <= 6 && words.every((word) => fromName.has(word));
20
+ }
21
+ const isDoc = (comment) => comment.type === 'Block' && comment.value.startsWith('*');
22
+ /** A comment's lines of prose: no doc-comment stars, blank lines or directives. */
23
+ const textLines = (comment) => {
24
+ const lines = comment.value
25
+ .split('\n')
26
+ .map((line) => line.replace(/^\s*\*?\s?/u, '').trim())
27
+ .filter((line) => line !== '' && line !== '*');
28
+ // A block that opens with a directive, such as a multi-line `oxlint-disable`, is all directive.
29
+ if (comment.type === 'Block' && DIRECTIVE.test(lines[0] ?? ''))
30
+ return [];
31
+ return lines.filter((line) => !DIRECTIVE.test(line));
32
+ };
33
+ /** A comment that holds only directives, such as `// oxlint-disable-next-line rule -- reason`. */
34
+ const isDirective = (comment) => comment.value.trim() !== '' && textLines(comment).length === 0;
35
+ /** Adjacent `//` lines at one indent read as one comment; a directive stands alone. */
36
+ function commentGroups(comments, text) {
37
+ const groups = [];
38
+ for (const comment of comments) {
39
+ if (comment.type === 'Shebang')
40
+ continue;
41
+ const group = groups.at(-1);
42
+ const previous = group?.at(-1);
43
+ const continues = group !== undefined &&
44
+ previous !== undefined &&
45
+ !isDirective(previous) &&
46
+ !isDirective(comment) &&
47
+ previous?.type === 'Line' &&
48
+ comment.type === 'Line' &&
49
+ previous.loc.start.column === comment.loc.start.column &&
50
+ /^[ \t]*\r?\n[ \t]*$/u.test(text.slice(previous.end, comment.start));
51
+ if (continues)
52
+ group.push(comment);
53
+ else
54
+ groups.push([comment]);
55
+ }
56
+ return groups;
57
+ }
58
+ /** The doc comment directly above a node, looking past directives such as `oxlint-disable-next-line`. */
59
+ function docBefore(node, sourceCode) {
60
+ const comments = sourceCode.getCommentsBefore(node);
61
+ let comment = comments.pop();
62
+ while (comment !== undefined && !isDoc(comment) && textLines(comment).length === 0)
63
+ comment = comments.pop();
64
+ return comment !== undefined && isDoc(comment) ? comment : undefined;
65
+ }
66
+ const isExport = (node) => node.type === 'ExportNamedDeclaration' ||
67
+ node.type === 'ExportDefaultDeclaration' ||
68
+ node.type === 'ExportAllDeclaration';
69
+ /** Top-level statements that export, and declarations of a binding that `export { name }` or `export default name` exports. */
70
+ function exportedStatements(program, sourceCode) {
71
+ const names = new Set();
72
+ for (const statement of program.body) {
73
+ if (statement.type === 'ExportNamedDeclaration' &&
74
+ statement.declaration === null &&
75
+ statement.source === null) {
76
+ for (const specifier of statement.specifiers) {
77
+ if (specifier.local.type === 'Identifier')
78
+ names.add(specifier.local.name);
79
+ }
80
+ }
81
+ else if (statement.type === 'ExportDefaultDeclaration' &&
82
+ statement.declaration.type === 'Identifier') {
83
+ names.add(statement.declaration.name);
84
+ }
85
+ }
86
+ const exported = new Set();
87
+ for (const statement of program.body) {
88
+ if (isExport(statement)) {
89
+ exported.add(statement);
90
+ }
91
+ else if (statement.type === 'VariableDeclaration') {
92
+ for (const declarator of statement.declarations) {
93
+ const declared = sourceCode.getDeclaredVariables(declarator);
94
+ if (declared.some((variable) => names.has(variable.name)))
95
+ exported.add(declarator);
96
+ }
97
+ }
98
+ else if ('id' in statement &&
99
+ statement.id?.type === 'Identifier' &&
100
+ names.has(statement.id.name)) {
101
+ exported.add(statement);
102
+ }
103
+ }
104
+ return exported;
105
+ }
106
+ /** The statement a doc comment for an exported node sits above. */
107
+ const docTarget = (node) => node.type === 'VariableDeclarator' && node.parent !== null ? node.parent : node;
108
+ /** The name a declaration or member declares, for the doc comment above it. */
109
+ function nameOf(node) {
110
+ let target = node;
111
+ if (target.type === 'ExportNamedDeclaration' || target.type === 'ExportDefaultDeclaration')
112
+ target = target.declaration;
113
+ if (target?.type === 'VariableDeclaration')
114
+ target = target.declarations[0] ?? null;
115
+ if (target === null)
116
+ return undefined;
117
+ const id = 'key' in target ? target.key : 'id' in target ? target.id : undefined;
118
+ if (id?.type === 'Identifier')
119
+ return id.name;
120
+ if (id?.type === 'Literal' && typeof id.value === 'string')
121
+ return id.value;
122
+ return undefined;
123
+ }
124
+ /**
125
+ * Whether a suppression directive follows a comment group on the next lines, past other
126
+ * directives, so the group is its reason, as `require-suppression-reason` reads it.
127
+ */
128
+ function suppressionFollows(groups, index, ownLine) {
129
+ let line = groups[index]?.at(-1)?.loc.end.line ?? 0;
130
+ for (let next = index + 1; next < groups.length; next++) {
131
+ const comment = groups[next]?.[0];
132
+ if (comment === undefined || comment.loc.start.line !== line + 1)
133
+ return false;
134
+ // A reason may sit above a line that ends in `// oxlint-disable-line rule`.
135
+ if (!ownLine(comment))
136
+ return SUPPRESSION.test(comment.value);
137
+ if (SUPPRESSION.test(comment.value))
138
+ return true;
139
+ if (!isDirective(comment) && comment.value.replace(/[\s*]/gu, '') !== '')
140
+ return false;
141
+ line = comment.loc.end.line;
142
+ }
143
+ return false;
144
+ }
145
+ const FUNCTIONS = new Set([
146
+ 'ArrowFunctionExpression',
147
+ 'FunctionExpression',
148
+ 'FunctionDeclaration',
149
+ ]);
150
+ /** Whether a member belongs to an exported declaration and is public: not in a function body, not private. */
151
+ function isExposedMember(member, exported) {
152
+ let node = member;
153
+ for (;;) {
154
+ if (node.type === 'BlockStatement' || node.type === 'StaticBlock')
155
+ return false;
156
+ if ('accessibility' in node &&
157
+ (node.accessibility === 'private' || node.accessibility === 'protected')) {
158
+ return false;
159
+ }
160
+ if ('key' in node && node.key.type === 'PrivateIdentifier')
161
+ return false;
162
+ if (exported.has(node))
163
+ return true;
164
+ const parent = node.parent;
165
+ if (parent === null || parent.type === 'Program')
166
+ return false;
167
+ if (FUNCTIONS.has(parent.type) && 'body' in parent && parent.body === node)
168
+ return false;
169
+ node = parent;
170
+ }
171
+ }
172
+ /**
173
+ * Keep only comments that carry what the code can't: directives, licence headers, docs on exports,
174
+ * the reason above a suppression and comments that start with an allowed prefix such as `SAFETY:`.
175
+ * Each gets one line, a word limit and no doc that only repeats the name below it.
176
+ */
177
+ export const commentsRule = defineRule({
178
+ meta: {
179
+ type: 'suggestion',
180
+ docs: {
181
+ description: 'Keep only tagged comments, docs on exports and suppression reasons, each on one line.',
182
+ },
183
+ schema: [
184
+ {
185
+ type: 'object',
186
+ properties: {
187
+ maxWords: { type: 'integer', minimum: 1 },
188
+ multilineExportDocs: { type: 'boolean' },
189
+ allow: { type: 'array', items: { type: 'string', minLength: 1 } },
190
+ },
191
+ additionalProperties: false,
192
+ },
193
+ ],
194
+ defaultOptions: [
195
+ {
196
+ maxWords: 30,
197
+ multilineExportDocs: false,
198
+ allow: ['SAFETY', 'SYNC', 'WARNING'],
199
+ },
200
+ ],
201
+ messages: {
202
+ untagged: 'Remove this comment: put the meaning in names and the rationale in the PR. Comments that start with {{prefixes}}, directives, docs on exports and the reason above a suppression stay.',
203
+ multiLine: 'Keep this comment to one line. Leave the history to git and the PR.',
204
+ multiLineDoc: 'Keep this doc to one line. A file whose exports need longer docs sets `multilineExportDocs` in an override.',
205
+ tooLong: 'This comment has {{words}} words; the limit is {{max}}.',
206
+ restatesName: 'This doc only repeats the name below it. Say why, or say nothing.',
207
+ },
208
+ },
209
+ create(context) {
210
+ // SAFETY: oxlint validates the options against the schema above and fills in defaultOptions.
211
+ const [options] = context.options;
212
+ const { sourceCode } = context;
213
+ const isTagged = (line) => options.allow.some((prefix) => line.startsWith(`${prefix}:`) && line.slice(prefix.length + 1).trim() !== '');
214
+ const prefixes = options.allow.map((prefix) => `\`${prefix}:\``).join(', ');
215
+ const members = [];
216
+ const collect = (node) => {
217
+ members.push(node);
218
+ };
219
+ /** The first problem with a comment, as a message id and its data. */
220
+ const problem = (lines, kind, name) => {
221
+ if (kind === 'other' && !isTagged(lines[0] ?? ''))
222
+ return ['untagged', { prefixes }];
223
+ const exempt = kind === 'exportDoc' && options.multilineExportDocs;
224
+ if (!exempt) {
225
+ if (lines.length > 1)
226
+ return [kind === 'exportDoc' ? 'multiLineDoc' : 'multiLine'];
227
+ const words = lines.join(' ').split(/\s+/u).filter((word) => word !== '').length;
228
+ if (words > options.maxWords)
229
+ return ['tooLong', { words, max: options.maxWords }];
230
+ }
231
+ if (name !== undefined && restatesName(lines, name))
232
+ return ['restatesName'];
233
+ return undefined;
234
+ };
235
+ return {
236
+ TSPropertySignature: collect,
237
+ TSMethodSignature: collect,
238
+ TSIndexSignature: collect,
239
+ TSCallSignatureDeclaration: collect,
240
+ TSConstructSignatureDeclaration: collect,
241
+ TSEnumMember: collect,
242
+ PropertyDefinition: collect,
243
+ MethodDefinition: collect,
244
+ Property: collect,
245
+ 'Program:exit'(program) {
246
+ const exportedNodes = exportedStatements(program, sourceCode);
247
+ /** Export docs by where they start, with the name each documents: the first, when one declaration exports several. */
248
+ const exportDocs = new Map();
249
+ const addDoc = (target, name) => {
250
+ const doc = docBefore(target, sourceCode);
251
+ if (doc !== undefined && !exportDocs.has(doc.start))
252
+ exportDocs.set(doc.start, name);
253
+ };
254
+ for (const node of exportedNodes)
255
+ addDoc(docTarget(node), nameOf(node));
256
+ for (const member of members)
257
+ if (isExposedMember(member, exportedNodes))
258
+ addDoc(member, nameOf(member));
259
+ const codeStart = program.body[0]?.start ?? sourceCode.text.length;
260
+ const groups = commentGroups(sourceCode.getAllComments(), sourceCode.text);
261
+ const ownLine = (comment) => (sourceCode.lines[comment.loc.start.line - 1] ?? '')
262
+ .slice(0, comment.loc.start.column)
263
+ .trim() === '';
264
+ for (const [index, group] of groups.entries()) {
265
+ const first = group[0];
266
+ const last = group.at(-1);
267
+ if (first === undefined || last === undefined)
268
+ continue;
269
+ const licence = first.value.startsWith('!') ||
270
+ group.some((comment) => LICENSE.test(comment.value)) ||
271
+ (last.end <= codeStart && group.some((comment) => COPYRIGHT.test(comment.value)));
272
+ const lines = group.flatMap(textLines);
273
+ if (licence || lines.length === 0)
274
+ continue;
275
+ const kind = exportDocs.has(first.start)
276
+ ? 'exportDoc'
277
+ : ownLine(first) && suppressionFollows(groups, index, ownLine)
278
+ ? 'reason'
279
+ : 'other';
280
+ const found = problem(lines, kind, exportDocs.get(first.start));
281
+ if (found === undefined)
282
+ continue;
283
+ const [messageId, data] = found;
284
+ context.report({ loc: { start: first.loc.start, end: last.loc.end }, messageId, data });
285
+ }
286
+ },
287
+ };
288
+ },
289
+ });
@@ -0,0 +1,2 @@
1
+ /** Disallow inline disables of the type-assertion rules, and disables that name no rule at all. */
2
+ export declare const noDisabledTypeAssertionRulesRule: import("@oxlint/plugins").Rule;