@sshkeda/check 2.0.0 → 2.2.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.
Files changed (31) hide show
  1. package/README.md +1 -1
  2. package/docs/how-to-make-check-pass.md +2 -0
  3. package/package.json +1 -1
  4. package/src/internal/ban-abbreviated-words-in-declared-names.ts +4 -5
  5. package/src/internal/ban-deadlines-inside-tests.ts +4 -5
  6. package/src/internal/ban-dropped-failures-detached-fibers-sleeps-and-untraced-functions.ts +4 -5
  7. package/src/internal/ban-failures-collected-as-results.ts +4 -5
  8. package/src/internal/ban-fallbacks-of-named-recoveries.ts +6 -7
  9. package/src/internal/ban-fixed-values-in-recoveries.ts +331 -0
  10. package/src/internal/ban-reading-the-clock-and-sleeping-outside-effect.ts +4 -5
  11. package/src/internal/ban-recovering-file-system-exists.ts +12 -79
  12. package/src/internal/ban-timer-schedules-without-deadlines.ts +5 -6
  13. package/src/internal/ban-type-predicates.ts +4 -5
  14. package/src/internal/ban-what-a-file-is-not-granted.ts +9 -9
  15. package/src/internal/define-the-lint-plugin-and-configs.ts +6 -0
  16. package/src/internal/follow-the-steps-applied-to-an-effect.ts +100 -0
  17. package/src/internal/recognize-fixed-values.ts +318 -0
  18. package/src/internal/recognize-whole-library-error-tags.ts +6 -0
  19. package/src/internal/report-code-grants-nothing-uses.ts +122 -0
  20. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/internal/read-effect-tsgo-json-report.ts +13 -9
  21. package/src/lib/tasks/lib/enforce-file-layout/internal/file-layout-errors.ts +1 -1
  22. package/src/lib/tasks/lib/enforce-file-layout/internal/find-file-layout-violations.ts +3 -1
  23. package/src/lib/tasks/lib/enforce-file-layout/internal/find-module-layout-violations.ts +6 -4
  24. package/src/lib/tasks/lib/format-with-bun-fmt/internal/check-formatting-with-bun-fmt.ts +1 -1
  25. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-the-importer-graph.ts +12 -3
  26. package/src/lib/tasks/shared/check-each-nested-package.ts +1 -1
  27. package/src/lib/tasks/shared/classify-files-by-role.ts +7 -2
  28. package/src/lib/tasks/shared/list-package-files.ts +15 -2
  29. package/src/shared/bans-each-permission-lifts.ts +3 -0
  30. package/src/shared/record-and-grant-permissions-by-path.ts +59 -6
  31. /package/src/lib/tasks/{lib/format-with-bun-fmt/internal → shared}/find-symbolic-links.ts +0 -0
@@ -0,0 +1,318 @@
1
+ import type { ESTree, SourceCode } from "@oxlint/plugins";
2
+
3
+ import { stepOf } from "./follow-the-steps-applied-to-an-effect.ts";
4
+ import {
5
+ constantValue,
6
+ effectModuleOperation,
7
+ importedExpression,
8
+ isGlobalReference,
9
+ isPipeFunction,
10
+ memberName,
11
+ resolvedVariable,
12
+ unwrappedExpression,
13
+ } from "./resolve-what-an-expression-imports.ts";
14
+
15
+ const PIPE = "pipe";
16
+
17
+ const EFFECT_MODULES = ["Effect", "Stream", "Channel"] as const;
18
+
19
+ const FIXED_EFFECTS: ReadonlySet<string> = new Set(["void", "succeedNone", "empty"]);
20
+
21
+ const SUCCEEDING_OPERATIONS: ReadonlySet<string> = new Set(["succeed", "succeedSome"]);
22
+
23
+ const SIGN_OPERATORS: ReadonlySet<string> = new Set(["-", "+", "void"]);
24
+
25
+ const CONSTRUCTED_GLOBALS = ["Map", "Set", "Date", "Uint8Array"] as const;
26
+
27
+ const PRIMITIVE_GLOBAL_CALLS = [
28
+ { object: "Date", member: "now" },
29
+ { object: "process", member: "cwd" },
30
+ ] as const;
31
+
32
+ const GLOBAL_CALLS = [...PRIMITIVE_GLOBAL_CALLS, { object: "Uint8Array", member: "of" }] as const;
33
+
34
+ const MODULE_SCOPES: ReadonlySet<string> = new Set(["module", "global"]);
35
+
36
+ const OS_MODULES: ReadonlySet<string> = new Set(["node:os", "os"]);
37
+
38
+ const HOME_DIRECTORY = "homedir";
39
+
40
+ const CURRENT_TIME = [
41
+ { moduleName: "Clock", member: "currentTimeMillis" },
42
+ { moduleName: "DateTime", member: "now" },
43
+ ] as const;
44
+
45
+ const branchesOf = (expression: ESTree.Node): readonly ESTree.Node[] => {
46
+ const value = unwrappedExpression(expression);
47
+ if (value.type === "ConditionalExpression") {
48
+ return [...branchesOf(value.consequent), ...branchesOf(value.alternate)];
49
+ }
50
+ if (value.type === "SequenceExpression") {
51
+ const last = value.expressions.at(-1);
52
+ return last === undefined ? [] : branchesOf(last);
53
+ }
54
+ return [value];
55
+ };
56
+
57
+ export const returnedValuesIn = (statement: ESTree.Node | null): readonly ESTree.Node[] => {
58
+ if (statement === null) {
59
+ return [];
60
+ }
61
+ if (statement.type === "ReturnStatement") {
62
+ return statement.argument === null ? [] : branchesOf(statement.argument);
63
+ }
64
+ if (statement.type === "BlockStatement") {
65
+ return statement.body.flatMap((inner) => returnedValuesIn(inner));
66
+ }
67
+ if (statement.type === "IfStatement") {
68
+ return [...returnedValuesIn(statement.consequent), ...returnedValuesIn(statement.alternate)];
69
+ }
70
+ if (statement.type === "TryStatement") {
71
+ return [
72
+ ...returnedValuesIn(statement.block),
73
+ ...returnedValuesIn(statement.handler?.body ?? null),
74
+ ];
75
+ }
76
+ if (statement.type === "SwitchStatement") {
77
+ return statement.cases.flatMap((switchCase) =>
78
+ switchCase.consequent.flatMap((inner) => returnedValuesIn(inner)),
79
+ );
80
+ }
81
+ return statement.type === "LabeledStatement" ? returnedValuesIn(statement.body) : [];
82
+ };
83
+
84
+ const FUNCTION_WRAPPERS: ReadonlySet<string> = new Set(["fn", "fnUntraced"]);
85
+
86
+ const isFunctionWrapper = (callee: ESTree.Node, sourceCode: SourceCode) => {
87
+ const operation = effectModuleOperation(callee, sourceCode, "Effect");
88
+ return operation !== undefined && FUNCTION_WRAPPERS.has(operation);
89
+ };
90
+
91
+ const wrappedFunction = (call: ESTree.CallExpression, sourceCode: SourceCode) => {
92
+ const isNamedWrapper =
93
+ call.callee.type === "CallExpression" && isFunctionWrapper(call.callee.callee, sourceCode);
94
+ const isWrapped = isNamedWrapper || isFunctionWrapper(call.callee, sourceCode);
95
+ const [wrapped] = call.arguments;
96
+ const isWrappingAFunction = isWrapped && wrapped !== undefined;
97
+ return isWrappingAFunction ? constantValue(wrapped, sourceCode) : undefined;
98
+ };
99
+
100
+ export const handlerFunction = (handler: ESTree.Node, sourceCode: SourceCode) => {
101
+ const resolved = constantValue(handler, sourceCode);
102
+ const unwrapped =
103
+ resolved.type === "CallExpression" ? wrappedFunction(resolved, sourceCode) : resolved;
104
+ const isFunction =
105
+ unwrapped?.type === "ArrowFunctionExpression" ||
106
+ unwrapped?.type === "FunctionExpression" ||
107
+ unwrapped?.type === "FunctionDeclaration";
108
+ return isFunction ? unwrapped : undefined;
109
+ };
110
+
111
+ export const returnedBranches = (handler: ESTree.Node, sourceCode: SourceCode) => {
112
+ const body = handlerFunction(handler, sourceCode)?.body ?? null;
113
+ if (body === null) {
114
+ return [];
115
+ }
116
+ return body.type === "BlockStatement" ? returnedValuesIn(body) : branchesOf(body);
117
+ };
118
+
119
+ const isGlobalCall = (
120
+ callee: ESTree.Node,
121
+ sourceCode: SourceCode,
122
+ calls: readonly { readonly object: string; readonly member: string }[] = GLOBAL_CALLS,
123
+ ) =>
124
+ callee.type === "MemberExpression" &&
125
+ calls.some(
126
+ ({ object, member }) =>
127
+ memberName(callee) === member && isGlobalReference(callee.object, sourceCode, object),
128
+ );
129
+
130
+ const isHomeDirectoryCall = (callee: ESTree.Node, sourceCode: SourceCode) => {
131
+ const imported = importedExpression(callee, sourceCode);
132
+ return (
133
+ imported !== undefined &&
134
+ OS_MODULES.has(imported.module) &&
135
+ imported.members.at(-1) === HOME_DIRECTORY
136
+ );
137
+ };
138
+
139
+ const isFixedOptionOrResult = (call: ESTree.CallExpression, sourceCode: SourceCode) => {
140
+ const optionOperation = effectModuleOperation(call.callee, sourceCode, "Option");
141
+ const resultOperation = effectModuleOperation(call.callee, sourceCode, "Result");
142
+ const isNone = optionOperation === "none" && call.arguments.length === 0;
143
+ const wrapsOneValue =
144
+ (optionOperation === "some" || resultOperation === "succeed") && call.arguments.length === 1;
145
+ return isNone || wrapsOneValue;
146
+ };
147
+
148
+ const isImmutableByNature = (value: ESTree.Node, sourceCode: SourceCode): boolean => {
149
+ if (value.type === "Literal") {
150
+ return typeof value.value !== "object" || value.value === null;
151
+ }
152
+ if (value.type === "TemplateLiteral") {
153
+ return value.expressions.length === 0;
154
+ }
155
+ if (value.type === "Identifier") {
156
+ return isGlobalReference(value, sourceCode, "undefined");
157
+ }
158
+ if (value.type === "UnaryExpression") {
159
+ return (
160
+ SIGN_OPERATORS.has(value.operator) &&
161
+ isImmutableByNature(constantValue(value.argument, sourceCode), sourceCode)
162
+ );
163
+ }
164
+ if (value.type !== "CallExpression") {
165
+ return false;
166
+ }
167
+ const isPrimitiveCall =
168
+ isGlobalCall(value.callee, sourceCode, PRIMITIVE_GLOBAL_CALLS) ||
169
+ isHomeDirectoryCall(value.callee, sourceCode);
170
+ const isImmutableCall = isPrimitiveCall || isFixedOptionOrResult(value, sourceCode);
171
+ return (
172
+ isImmutableCall &&
173
+ value.arguments.every(
174
+ (argument) =>
175
+ argument.type !== "SpreadElement" &&
176
+ isImmutableByNature(constantValue(argument, sourceCode), sourceCode),
177
+ )
178
+ );
179
+ };
180
+
181
+ const valueOfAnUnchangeableBinding = (node: ESTree.Node, sourceCode: SourceCode) => {
182
+ const value = constantValue(node, sourceCode);
183
+ const variable = resolvedVariable(unwrappedExpression(node), sourceCode);
184
+ const isDeclaredAtModuleScope =
185
+ variable === undefined || MODULE_SCOPES.has(variable.scope.variableScope.type);
186
+ const isResolvable = isDeclaredAtModuleScope || isImmutableByNature(value, sourceCode);
187
+ return isResolvable ? value : unwrappedExpression(node);
188
+ };
189
+
190
+ export const isFixedValue = (node: ESTree.Node, sourceCode: SourceCode): boolean => {
191
+ const value = valueOfAnUnchangeableBinding(node, sourceCode);
192
+ const areFixedArguments = (callArguments: readonly ESTree.Node[]) =>
193
+ callArguments.every(
194
+ (argument) => argument.type !== "SpreadElement" && isFixedValue(argument, sourceCode),
195
+ );
196
+ const isFixedProperty = (property: ESTree.Node) =>
197
+ property.type === "Property" &&
198
+ !property.computed &&
199
+ !property.method &&
200
+ property.kind === "init" &&
201
+ isFixedValue(property.value, sourceCode);
202
+ if (value.type === "Literal") {
203
+ return typeof value.value !== "object" || value.value === null;
204
+ }
205
+ if (value.type === "TemplateLiteral") {
206
+ return value.expressions.length === 0;
207
+ }
208
+ if (value.type === "Identifier") {
209
+ return isGlobalReference(value, sourceCode, "undefined");
210
+ }
211
+ if (value.type === "UnaryExpression") {
212
+ return SIGN_OPERATORS.has(value.operator) && isFixedValue(value.argument, sourceCode);
213
+ }
214
+ if (value.type === "ArrayExpression") {
215
+ return value.elements.every(
216
+ (element) =>
217
+ element !== null && element.type !== "SpreadElement" && isFixedValue(element, sourceCode),
218
+ );
219
+ }
220
+ if (value.type === "ObjectExpression") {
221
+ return value.properties.every((property) => isFixedProperty(property));
222
+ }
223
+ if (value.type === "NewExpression") {
224
+ const isConstructedGlobal = CONSTRUCTED_GLOBALS.some((name) =>
225
+ isGlobalReference(value.callee, sourceCode, name),
226
+ );
227
+ return isConstructedGlobal && areFixedArguments(value.arguments);
228
+ }
229
+ if (value.type !== "CallExpression") {
230
+ return false;
231
+ }
232
+ const isFixedCall =
233
+ isGlobalCall(value.callee, sourceCode) ||
234
+ isHomeDirectoryCall(value.callee, sourceCode) ||
235
+ isFixedOptionOrResult(value, sourceCode);
236
+ return isFixedCall && areFixedArguments(value.arguments);
237
+ };
238
+
239
+ const isCurrentTime = (node: ESTree.Node, sourceCode: SourceCode) =>
240
+ CURRENT_TIME.some(
241
+ ({ moduleName, member }) => effectModuleOperation(node, sourceCode, moduleName) === member,
242
+ );
243
+
244
+ const isFixedEffectMember = (node: ESTree.Node, sourceCode: SourceCode) =>
245
+ isCurrentTime(node, sourceCode) ||
246
+ EFFECT_MODULES.some((moduleName) => {
247
+ const operation = effectModuleOperation(node, sourceCode, moduleName);
248
+ return operation !== undefined && FIXED_EFFECTS.has(operation);
249
+ });
250
+
251
+ const fixedValueAfterTheLastStep = (steps: readonly ESTree.Node[], sourceCode: SourceCode) => {
252
+ const last = steps.at(-1);
253
+ if (last === undefined) {
254
+ return;
255
+ }
256
+ const { operation, callArguments } = stepOf(last, sourceCode);
257
+ const [value] = callArguments;
258
+ if (operation === "asVoid") {
259
+ return callArguments.length === 0 ? last : undefined;
260
+ }
261
+ const isFixedReplacement =
262
+ operation === "as" && value !== undefined && isFixedValue(value, sourceCode);
263
+ return isFixedReplacement ? value : undefined;
264
+ };
265
+
266
+ const fixedReturnedValue = (
267
+ callArguments: readonly ESTree.Node[],
268
+ sourceCode: SourceCode,
269
+ ): ESTree.Node | undefined =>
270
+ callArguments
271
+ .flatMap((argument) => returnedBranches(argument, sourceCode))
272
+ .find((branch) => isFixedValue(branch, sourceCode));
273
+
274
+ const fixedValueOfEffectCall = (
275
+ call: ESTree.CallExpression,
276
+ sourceCode: SourceCode,
277
+ ): ESTree.Node | undefined => {
278
+ const { callee, arguments: callArguments } = call;
279
+ const isPipeMethod = callee.type === "MemberExpression" && memberName(callee) === PIPE;
280
+ if (isPipeMethod) {
281
+ return fixedValueAfterTheLastStep(callArguments, sourceCode);
282
+ }
283
+ if (isPipeFunction(callee, sourceCode)) {
284
+ return fixedValueAfterTheLastStep(callArguments.slice(1), sourceCode);
285
+ }
286
+ const operation = EFFECT_MODULES.map((moduleName) =>
287
+ effectModuleOperation(callee, sourceCode, moduleName),
288
+ ).find((found) => found !== undefined);
289
+ const [first, second] = callArguments;
290
+ if (operation === undefined) {
291
+ return;
292
+ }
293
+ if (SUCCEEDING_OPERATIONS.has(operation)) {
294
+ const isFixedSuccess =
295
+ callArguments.length === 1 && first !== undefined && isFixedValue(first, sourceCode);
296
+ return isFixedSuccess ? first : undefined;
297
+ }
298
+ if (operation === "as") {
299
+ const isFixedReplacement = second !== undefined && isFixedValue(second, sourceCode);
300
+ return isFixedReplacement ? second : undefined;
301
+ }
302
+ if (operation === "asVoid") {
303
+ return callArguments.length === 1 ? call : undefined;
304
+ }
305
+ const computesItsValue = operation === "sync" || operation === "gen";
306
+ return computesItsValue ? fixedReturnedValue(callArguments, sourceCode) : undefined;
307
+ };
308
+
309
+ export const fixedOutcomeOf = (node: ESTree.Node, sourceCode: SourceCode) => {
310
+ if (isFixedValue(node, sourceCode)) {
311
+ return node;
312
+ }
313
+ const value = constantValue(node, sourceCode);
314
+ if (value.type === "CallExpression") {
315
+ return fixedValueOfEffectCall(value, sourceCode);
316
+ }
317
+ return isFixedEffectMember(value, sourceCode) ? node : undefined;
318
+ };
@@ -0,0 +1,6 @@
1
+ const LIBRARY_ERROR_SUFFIX = "Error";
2
+
3
+ const LIBRARY_ERROR_TAGS_WITHOUT_THE_SUFFIX: ReadonlySet<string> = new Set(["CommandFailed"]);
4
+
5
+ export const isWholeLibraryErrorTag = (tag: string) =>
6
+ tag.endsWith(LIBRARY_ERROR_SUFFIX) || LIBRARY_ERROR_TAGS_WITHOUT_THE_SUFFIX.has(tag);
@@ -0,0 +1,122 @@
1
+ import type { Context, CreateRule, Visitor } from "@oxlint/plugins";
2
+ import { Schema } from "effect";
3
+
4
+ import {
5
+ HANDLES_EVERY_FAILURE,
6
+ PERMISSION_BANS,
7
+ RULES_EACH_PERMISSION_LIFTS,
8
+ SHORT_NAMES,
9
+ TRUSTS_UNVERIFIED_TYPES,
10
+ unusedGrantMessage,
11
+ } from "../shared/bans-each-permission-lifts.ts";
12
+ import {
13
+ CLOCK_RULE,
14
+ CODE_GRANTS,
15
+ FAILURES_AS_RESULTS_RULE,
16
+ INSIDE_THE_TEST_HOME,
17
+ rulesACodeGrantChanges,
18
+ SCHEDULES_RULE,
19
+ SLEEP_RULE,
20
+ TEST_TIMEOUTS_RULE,
21
+ TYPE_PREDICATES_RULE,
22
+ UNNAMED_FALLBACKS_RULE,
23
+ } from "../shared/record-and-grant-permissions-by-path.ts";
24
+ import { noAbbreviations } from "./ban-abbreviated-words-in-declared-names.ts";
25
+ import { noTestTimeouts } from "./ban-deadlines-inside-tests.ts";
26
+ import { effectOperationRule } from "./ban-dropped-failures-detached-fibers-sleeps-and-untraced-functions.ts";
27
+ import { noFailuresAsResults } from "./ban-failures-collected-as-results.ts";
28
+ import { noUnnamedFallbacks } from "./ban-fallbacks-of-named-recoveries.ts";
29
+ import { noClockReadsAndSleeps } from "./ban-reading-the-clock-and-sleeping-outside-effect.ts";
30
+ import { noSchedules } from "./ban-timer-schedules-without-deadlines.ts";
31
+ import { noTypePredicates } from "./ban-type-predicates.ts";
32
+ import { mergedVisitors, permissionBanRule } from "./ban-what-a-file-is-not-granted.ts";
33
+ import { decodeRuleOptions, ruleOptionsJsonSchema } from "./describe-and-decode-rule-options.ts";
34
+
35
+ const RULES_CODE_GRANTS_CHANGE: ReadonlyMap<
36
+ string,
37
+ {
38
+ readonly create: (context: Pick<Context, "options" | "report" | "sourceCode">) => Visitor;
39
+ }
40
+ > = new Map(
41
+ Object.entries({
42
+ [PERMISSION_BANS[HANDLES_EVERY_FAILURE].ruleName]: permissionBanRule(HANDLES_EVERY_FAILURE),
43
+ [PERMISSION_BANS[TRUSTS_UNVERIFIED_TYPES].ruleName]: permissionBanRule(TRUSTS_UNVERIFIED_TYPES),
44
+ [FAILURES_AS_RESULTS_RULE]: noFailuresAsResults,
45
+ [UNNAMED_FALLBACKS_RULE]: noUnnamedFallbacks,
46
+ [SLEEP_RULE]: effectOperationRule(SLEEP_RULE),
47
+ [CLOCK_RULE]: noClockReadsAndSleeps,
48
+ [SCHEDULES_RULE]: noSchedules,
49
+ [TEST_TIMEOUTS_RULE]: noTestTimeouts,
50
+ [RULES_EACH_PERMISSION_LIFTS[SHORT_NAMES]]: noAbbreviations,
51
+ [TYPE_PREDICATES_RULE]: noTypePredicates,
52
+ }).map(([name, rule]) => [`sshkeda/${name}`, rule] as const),
53
+ );
54
+
55
+ const UNUSED_CODE_GRANT_OPTIONS = Schema.Struct({
56
+ permissions: Schema.optionalKey(Schema.Array(Schema.Literals(CODE_GRANTS))),
57
+ testHome: Schema.optionalKey(Schema.Literal(INSIDE_THE_TEST_HOME)),
58
+ });
59
+
60
+ export const noUnusedCodeGrants = {
61
+ meta: {
62
+ type: "problem",
63
+ messages: { unusedGrant: unusedGrantMessage("{{permission}}") },
64
+ schema: ruleOptionsJsonSchema(UNUSED_CODE_GRANT_OPTIONS),
65
+ },
66
+ create(context) {
67
+ const { sourceCode } = context;
68
+ const options = decodeRuleOptions(UNUSED_CODE_GRANT_OPTIONS, context.options);
69
+ const isInTheTestHome = options?.testHome === INSIDE_THE_TEST_HOME;
70
+ const runUnder = (ruleId: string, ruleOptions: Context["options"]) => {
71
+ const rule = RULES_CODE_GRANTS_CHANGE.get(ruleId);
72
+ if (rule === undefined) {
73
+ return [];
74
+ }
75
+ const reported = new Set<unknown>();
76
+ const visitor = rule.create({
77
+ sourceCode,
78
+ options: ruleOptions,
79
+ report: (diagnostic) => {
80
+ reported.add(diagnostic.node ?? diagnostic);
81
+ },
82
+ });
83
+ return [{ visitor, reported }];
84
+ };
85
+ const watched = (options?.permissions ?? []).map((permission) => {
86
+ const changed = rulesACodeGrantChanges(permission, isInTheTestHome);
87
+ return {
88
+ permission,
89
+ withoutTheGrant: changed
90
+ .filter(({ isOnWithoutTheGrant }) => isOnWithoutTheGrant)
91
+ .flatMap(({ ruleId }) => runUnder(ruleId, [])),
92
+ withTheGrant: changed.flatMap(({ ruleId, granted }) =>
93
+ granted === "off" ? [] : runUnder(ruleId, [granted[1]]),
94
+ ),
95
+ };
96
+ });
97
+ const isUsed = ({ withoutTheGrant, withTheGrant }: (typeof watched)[number]) => {
98
+ const stillReported = new Set(withTheGrant.flatMap(({ reported }) => [...reported]));
99
+ return withoutTheGrant.some(({ reported }) =>
100
+ [...reported].some((node) => !stillReported.has(node)),
101
+ );
102
+ };
103
+ return mergedVisitors([
104
+ ...watched.flatMap(({ withoutTheGrant, withTheGrant }) =>
105
+ [...withoutTheGrant, ...withTheGrant].map(({ visitor }) => visitor),
106
+ ),
107
+ {
108
+ "Program:exit"(node) {
109
+ for (const grant of watched) {
110
+ if (!isUsed(grant)) {
111
+ context.report({
112
+ node,
113
+ messageId: "unusedGrant",
114
+ data: { permission: grant.permission },
115
+ });
116
+ }
117
+ }
118
+ },
119
+ },
120
+ ]);
121
+ },
122
+ } satisfies CreateRule;
@@ -1,7 +1,10 @@
1
1
  import { Effect, Schema } from "effect";
2
2
 
3
+ import { distinctPrintedErrors } from "../../../shared/check-each-nested-package.ts";
3
4
  import { decodedReport } from "../../../shared/run-tools-and-decode-their-reports.ts";
4
5
 
6
+ const PROJECT_WIDE_DIAGNOSTICS: ReadonlySet<string> = new Set(["duplicatePackage"]);
7
+
5
8
  const UPSTREAM_MESSAGE_REWRITES: ReadonlyMap<string, string> = new Map([
6
9
  ["effect(schemaNumber)", "Schema.Number accepts NaN, Infinity and -Infinity"],
7
10
  ]);
@@ -25,15 +28,16 @@ export const effectViolationsReport = (program: string, standardOutput: string)
25
28
  ? Effect.succeed({ violations: [], notes: [] })
26
29
  : decodedReport(program, Schema.decodeEffect(EFFECT_VIOLATIONS_REPORT), standardOutput).pipe(
27
30
  Effect.map((report) => ({
28
- violations: report.diagnostics.map((reported) => {
29
- const tag = `effect(${reported.name})`;
30
- const location = `${reported.file}:${reported.line}:${reported.column}`;
31
- return {
32
- tag,
33
- location,
34
- message: UPSTREAM_MESSAGE_REWRITES.get(tag) ?? reported.message,
35
- };
36
- }),
31
+ violations: distinctPrintedErrors(
32
+ report.diagnostics.map((reported) => {
33
+ const tag = `effect(${reported.name})`;
34
+ const message = UPSTREAM_MESSAGE_REWRITES.get(tag) ?? reported.message;
35
+ const location = `${reported.file}:${reported.line}:${reported.column}`;
36
+ return PROJECT_WIDE_DIAGNOSTICS.has(reported.name)
37
+ ? { tag, message }
38
+ : { tag, location, message };
39
+ }),
40
+ ),
37
41
  notes: [],
38
42
  })),
39
43
  );
@@ -99,7 +99,7 @@ export class DirectoryOutsideModuleLayout extends Schema.TaggedError<DirectoryOu
99
99
  { location: Schema.String, module: Schema.String },
100
100
  ) {
101
101
  public override get message() {
102
- return `is a directory in the module ${this.module}/ other than ${INTERNAL_DIRECTORY_NAME}/, ${SHARED_DIRECTORY_NAME}/ or ${LIBRARY_DIRECTORY_NAME}/`;
102
+ return `is a directory in the module ${this.module}/ other than ${INTERNAL_DIRECTORY_NAME}/, ${SHARED_DIRECTORY_NAME}/ or ${LIBRARY_DIRECTORY_NAME}/. Move it to ${this.module}/${LIBRARY_DIRECTORY_NAME}/${fileNameOf(this.location)}/`;
103
103
  }
104
104
  }
105
105
 
@@ -35,6 +35,7 @@ import {
35
35
  TEST_DIRECTORY,
36
36
  } from "../../../../../shared/test-home-directories.ts";
37
37
  import {
38
+ MODULE_ROOT_DIRECTORIES,
38
39
  enclosingDirectoriesOf,
39
40
  isRootSupportFile,
40
41
  repeatsSourceNeverImportsScripts,
@@ -298,7 +299,8 @@ export const sourceViolations = (
298
299
  }
299
300
 
300
301
  const isSourceOutsideModuleImplementation =
301
- (isWithin(path, SOURCE_DIRECTORY) || isWithin(path, TEST_DIRECTORY)) &&
302
+ MODULE_ROOT_DIRECTORIES.has(path.split("/")[0] ?? "") &&
303
+ !isTopLevelScript(path) &&
302
304
  !isLibraryDirectoryOfAModule(directoryOf(path)) &&
303
305
  !isEntryFileName(fileNameOf(path)) &&
304
306
  !isDeclarationFile(path) &&
@@ -4,8 +4,11 @@ import {
4
4
  LAYOUT_DIRECTORY_NAMES,
5
5
  LIBRARY_DIRECTORY_NAME,
6
6
  } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
7
- import { SOURCE_DIRECTORY, TEST_DIRECTORY } from "../../../../../shared/test-home-directories.ts";
8
- import { directoryOf, enclosingDirectoriesOf } from "../../../shared/classify-files-by-role.ts";
7
+ import {
8
+ directoryOf,
9
+ enclosingDirectoriesOf,
10
+ MODULE_ROOT_DIRECTORIES,
11
+ } from "../../../shared/classify-files-by-role.ts";
9
12
  import {
10
13
  DirectoryOutsideModuleLayout,
11
14
  FileInLibraryDirectory,
@@ -16,8 +19,7 @@ import {
16
19
  export const isModuleDirectory = (directory: string): boolean => {
17
20
  const parent = directoryOf(directory);
18
21
  return (
19
- directory === SOURCE_DIRECTORY ||
20
- directory === TEST_DIRECTORY ||
22
+ MODULE_ROOT_DIRECTORIES.has(directory) ||
21
23
  (fileNameOf(parent) === LIBRARY_DIRECTORY_NAME && isModuleDirectory(directoryOf(parent)))
22
24
  );
23
25
  };
@@ -4,6 +4,7 @@ import { FORMAT_CONFIG_FILE } from "../../../../../shared/config-file-names.ts";
4
4
  import { printableError } from "../../../../../shared/format-reported-failures.ts";
5
5
  import { enclosingDirectoriesOf } from "../../../shared/classify-files-by-role.ts";
6
6
  import { encodeJson } from "../../../shared/encode-compact-json.ts";
7
+ import { isSymbolicLink } from "../../../shared/find-symbolic-links.ts";
7
8
  import {
8
9
  failQuietly,
9
10
  quietViolations,
@@ -13,7 +14,6 @@ import {
13
14
  mergedExit,
14
15
  runTool,
15
16
  } from "../../../shared/run-tools-and-decode-their-reports.ts";
16
- import { isSymbolicLink } from "./find-symbolic-links.ts";
17
17
  import { UnformattedFile } from "./unformatted-file-errors.ts";
18
18
 
19
19
  export const FORMATTED_PACKAGE_DIRECTORY = ".";
@@ -3,7 +3,10 @@ import { parseSync } from "oxc-parser";
3
3
  import type { ImportNameKind } from "oxc-parser";
4
4
 
5
5
  import { FORMAT_CONFIG_FILE } from "../../../../../shared/config-file-names.ts";
6
+ import { isWithin } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
7
+ import { SOURCE_DIRECTORY } from "../../../../../shared/test-home-directories.ts";
6
8
  import {
9
+ MODULE_ROOT_DIRECTORIES,
7
10
  isDeclarationFile,
8
11
  isTopLevelScript,
9
12
  isRootSupportFile,
@@ -253,15 +256,21 @@ export const findTheImporterGraph = (projectFile: string) =>
253
256
  ]);
254
257
  const importers = new Map<string, Set<string>>();
255
258
  for (const [importer, parsed] of files) {
256
- const isCountedImporter = reachable.has(importer) && !isUnderTestDirectory(importer);
259
+ const isCountedImporter = reachable.has(importer);
257
260
  for (const use of isCountedImporter ? parsed.uses : []) {
258
- if (use.file !== importer) {
261
+ const isCountedUse =
262
+ use.file !== importer &&
263
+ (!isUnderTestDirectory(importer) || !isWithin(use.file, SOURCE_DIRECTORY));
264
+ if (isCountedUse) {
259
265
  importers.set(use.file, (importers.get(use.file) ?? new Set()).add(importer));
260
266
  }
261
267
  }
262
268
  }
263
269
  const importersOf = (file: string) => [...(importers.get(file) ?? [])];
264
- const moduleDirectories = moduleDirectoriesAmong(paths);
270
+ const moduleDirectories = new Set([
271
+ ...MODULE_ROOT_DIRECTORIES,
272
+ ...moduleDirectoriesAmong(paths),
273
+ ]);
265
274
  return {
266
275
  paths,
267
276
  files,
@@ -39,7 +39,7 @@ const locatedInPackage = (
39
39
  message: printable.message,
40
40
  };
41
41
 
42
- const distinctPrintedErrors = (printables: readonly PrintableError[]) => {
42
+ export const distinctPrintedErrors = (printables: readonly PrintableError[]) => {
43
43
  const printedByLocation = new Map<string | undefined, Set<string>>();
44
44
  return printables.filter(({ tag, location, message }) => {
45
45
  const printed = printedByLocation.get(location) ?? new Set<string>();
@@ -63,8 +63,13 @@ export const isTestEntryFile = (path: string) =>
63
63
 
64
64
  export const isRootSupportFile = (path: string) => !path.includes("/") && toolFileIsPlaced(path);
65
65
 
66
- export const isSpecialContainer = (directory: string) =>
67
- directory === "" || directory === SCRIPTS_DIRECTORY;
66
+ export const isSpecialContainer = (directory: string) => directory === "";
67
+
68
+ export const MODULE_ROOT_DIRECTORIES: ReadonlySet<string> = new Set([
69
+ SOURCE_DIRECTORY,
70
+ TEST_DIRECTORY,
71
+ SCRIPTS_DIRECTORY,
72
+ ]);
68
73
 
69
74
  export const isStrictlyUnder = (directory: string, scope: string) =>
70
75
  directory !== scope && (scope === "" || directory.startsWith(`${scope}/`));
@@ -3,6 +3,7 @@ import { Effect, FileSystem, Option, Path, References } from "effect";
3
3
 
4
4
  import { enclosingDirectoriesOf } from "./classify-files-by-role.ts";
5
5
  import { PACKAGE_MANIFEST_FILE } from "./find-named-package-manifests.ts";
6
+ import { isSymbolicLink } from "./find-symbolic-links.ts";
6
7
  import { namedPackageManifestAt } from "./read-named-package-manifests.ts";
7
8
 
8
9
  const isNamedPackageDirectory = (directory: string) =>
@@ -29,9 +30,21 @@ export const nestedPackageDirectoriesAmong = (
29
30
  export const isInsideAnyDirectory = (relativePath: string, directories: readonly string[]) =>
30
31
  directories.some((directory) => relativePath.startsWith(`${directory}/`));
31
32
 
32
- const existingListedFiles = (packageDirectory: string, pathspecs: readonly string[]) =>
33
+ const isExistingNonDirectory = (location: string) =>
33
34
  Effect.gen(function* () {
34
35
  const fileSystem = yield* FileSystem.FileSystem;
36
+ const exists = yield* fileSystem.exists(location);
37
+ if (!exists) {
38
+ return false;
39
+ }
40
+ if (yield* isSymbolicLink(location)) {
41
+ return true;
42
+ }
43
+ return (yield* fileSystem.stat(location)).type !== "Directory";
44
+ });
45
+
46
+ const existingListedFiles = (packageDirectory: string, pathspecs: readonly string[]) =>
47
+ Effect.gen(function* () {
35
48
  const path = yield* Path.Path;
36
49
  const listed = yield* Task.exec(
37
50
  "git",
@@ -40,7 +53,7 @@ const existingListedFiles = (packageDirectory: string, pathspecs: readonly strin
40
53
  ).pipe(Effect.provideService(References.MinimumLogLevel, "Warn"));
41
54
  return yield* Effect.filter(
42
55
  new Set(listed.split("\0").filter((file) => file !== "")),
43
- (file) => fileSystem.exists(path.join(packageDirectory, file)),
56
+ (file) => isExistingNonDirectory(path.join(packageDirectory, file)),
44
57
  { concurrency: "unbounded" },
45
58
  );
46
59
  });
@@ -401,6 +401,9 @@ export const BANS_NO_GRANT_LIFTS = "onlyThoseNoGrantLifts";
401
401
 
402
402
  export const UNUSED_GRANT_REPORTED = "reported";
403
403
 
404
+ export const unusedGrantMessage = (permission: string) =>
405
+ `this file is granted ${permission}, but uses nothing ${permission} allows`;
406
+
404
407
  export const bansNoGrantLifts = (permission: keyof typeof PERMISSION_BANS) => {
405
408
  const entry = PERMISSION_BANS[permission];
406
409
  return "bannedEvenWhenGranted" in entry ? entry.bannedEvenWhenGranted.bans : [];