@sshkeda/check 1.1.0 → 2.1.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 (102) hide show
  1. package/README.md +7 -6
  2. package/docs/how-to-make-check-pass.md +4 -14
  3. package/package.json +4 -4
  4. package/src/internal/ban-abbreviated-words-in-declared-names.ts +0 -4
  5. package/src/internal/ban-checked-members-outside-calls.ts +8 -8
  6. package/src/internal/ban-comments.ts +0 -1
  7. package/src/internal/ban-comparing-or-switching-on-tag.ts +50 -10
  8. package/src/internal/ban-deadlines-inside-tests.ts +3 -4
  9. package/src/internal/ban-declared-values.ts +2 -5
  10. package/src/internal/ban-dropped-failures-detached-fibers-sleeps-and-untraced-functions.ts +0 -2
  11. package/src/internal/ban-failures-collected-as-results.ts +0 -4
  12. package/src/internal/ban-fallbacks-of-named-recoveries.ts +1 -29
  13. package/src/internal/ban-function-overloads.ts +0 -4
  14. package/src/internal/ban-global-error-in-failure-types.ts +10 -15
  15. package/src/internal/ban-instanceof-in-effect-recovery-callbacks.ts +17 -26
  16. package/src/internal/ban-let-and-effect-mutable-ref.ts +0 -8
  17. package/src/internal/ban-logic-in-index-files.ts +0 -3
  18. package/src/internal/ban-namespaces-used-without-a-member.ts +0 -3
  19. package/src/internal/ban-node-builtins-that-effect-replaces.ts +0 -3
  20. package/src/internal/ban-parsing-outside-data-without-a-schema.ts +0 -4
  21. package/src/internal/ban-re-exports.ts +54 -18
  22. package/src/internal/ban-reading-the-clock-and-sleeping-outside-effect.ts +88 -4
  23. package/src/internal/ban-recovering-file-system-exists.ts +300 -0
  24. package/src/internal/ban-retired-words-in-names.ts +1 -4
  25. package/src/internal/ban-retries-without-a-wait.ts +292 -0
  26. package/src/internal/ban-scanning-directories-with-bun-glob.ts +0 -3
  27. package/src/internal/ban-shebang-lines.ts +0 -4
  28. package/src/internal/ban-timer-globals-and-the-global-object.ts +0 -1
  29. package/src/internal/ban-timer-schedules-without-deadlines.ts +129 -45
  30. package/src/internal/ban-type-and-interface-declarations.ts +0 -4
  31. package/src/internal/ban-type-predicates.ts +0 -4
  32. package/src/internal/ban-unknown-in-function-signatures.ts +49 -13
  33. package/src/internal/ban-vague-error-class-names.ts +0 -4
  34. package/src/internal/ban-vague-file-names.ts +3 -7
  35. package/src/internal/ban-what-a-file-is-not-granted.ts +37 -14
  36. package/src/internal/ban-while-do-while-and-for-loops.ts +0 -4
  37. package/src/internal/ban-writing-captured-objects-inside-effect-callbacks.ts +210 -0
  38. package/src/internal/confine-service-declarations-to-granted-files.ts +0 -7
  39. package/src/internal/confine-the-stdio-service-to-terminal-output.ts +2 -16
  40. package/src/internal/define-the-lint-plugin-and-configs.ts +6 -0
  41. package/src/internal/keep-assertions-in-the-test-home-and-ban-test-runners.ts +0 -6
  42. package/src/internal/keep-effect-testing-helpers-in-test-files.ts +2 -14
  43. package/src/internal/require-a-named-const-for-compound-conditions.ts +0 -4
  44. package/src/internal/require-capital-snake-case-and-as-const-on-literal-constants.ts +0 -4
  45. package/src/internal/require-service-keys-to-end-with-their-class-name.ts +5 -2
  46. package/src/internal/resolve-what-an-expression-imports.ts +115 -28
  47. package/src/internal/visit-every-declared-name.ts +13 -0
  48. package/src/lib/tasks/internal/declare-the-check-task.ts +2 -0
  49. package/src/lib/tasks/internal/declare-the-checker-queries-task.ts +2 -1
  50. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/index.ts +2 -1
  51. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/internal/check-effect-diagnostics-with-effect-tsgo.ts +17 -0
  52. package/src/lib/tasks/lib/check-import-boundaries/internal/decide-what-each-home-may-import.ts +62 -0
  53. package/src/lib/tasks/lib/check-import-boundaries/internal/find-import-boundary-violations.ts +215 -187
  54. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/find-layer-provides-outside-program-starts.ts +13 -16
  55. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/layer-provide-errors.ts +2 -1
  56. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/resolve-imported-package-apis.ts +3 -1
  57. package/src/lib/tasks/lib/detect-duplicate-functions/index.ts +10 -0
  58. package/src/lib/tasks/lib/detect-duplicate-functions/internal/duplicate-function-errors.ts +23 -0
  59. package/src/lib/tasks/lib/detect-duplicate-functions/internal/find-duplicate-functions.ts +150 -0
  60. package/src/lib/tasks/lib/detect-duplicate-functions/internal/list-named-functions.ts +416 -0
  61. package/src/lib/tasks/lib/detect-inferrable-annotations/internal/find-inferrable-annotations.ts +31 -12
  62. package/src/lib/tasks/lib/enforce-file-layout/index.ts +6 -1
  63. package/src/lib/tasks/lib/enforce-file-layout/internal/file-layout-errors.ts +11 -1
  64. package/src/lib/tasks/lib/enforce-file-layout/internal/find-export-path-mismatches.ts +39 -7
  65. package/src/lib/tasks/lib/enforce-file-layout/internal/find-file-layout-violations.ts +11 -4
  66. package/src/lib/tasks/lib/enforce-file-layout/internal/find-module-layout-violations.ts +6 -4
  67. package/src/lib/tasks/lib/enforce-file-types/index.ts +6 -1
  68. package/src/lib/tasks/lib/format-with-bun-fmt/internal/declare-the-formatting-task.ts +3 -2
  69. package/src/lib/tasks/lib/judge-index-re-exports/internal/find-index-re-export-violations.ts +27 -21
  70. package/src/lib/tasks/lib/lint-with-oxlint/index.ts +2 -1
  71. package/src/lib/tasks/lib/lint-with-oxlint/internal/check-lint-rules-with-oxlint.ts +11 -8
  72. package/src/lib/tasks/lib/lint-with-oxlint/internal/read-oxlint-json-report.ts +18 -2
  73. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/export-placement-errors.ts +12 -1
  74. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-export-placement-violations.ts +75 -21
  75. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-package-entry-sources.ts +146 -0
  76. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-the-importer-graph.ts +24 -190
  77. package/src/lib/tasks/lib/refuse-disable-directives/index.ts +2 -1
  78. package/src/lib/tasks/lib/refuse-disable-directives/internal/find-disable-directives.ts +9 -3
  79. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/internal/find-error-mappings-to-done.ts +108 -9
  80. package/src/lib/tasks/lib/require-separate-service-layers/internal/find-service-layer-violations.ts +1 -5
  81. package/src/lib/tasks/lib/require-type-checking-every-linted-file/index.ts +2 -1
  82. package/src/lib/tasks/lib/require-type-checking-every-linted-file/internal/find-linted-files-not-type-checked.ts +2 -4
  83. package/src/lib/tasks/shared/check-each-nested-package.ts +13 -1
  84. package/src/lib/tasks/shared/classify-files-by-role.ts +12 -2
  85. package/src/lib/tasks/shared/count-the-line-of-an-offset.ts +20 -2
  86. package/src/lib/tasks/shared/create-the-module-resolver.ts +39 -23
  87. package/src/lib/tasks/shared/declare-lint-config-task.ts +2 -1
  88. package/src/lib/tasks/shared/declare-typescript-config-task.ts +30 -2
  89. package/src/lib/tasks/shared/find-unmet-typescript-config-requirements.ts +19 -6
  90. package/src/lib/tasks/shared/list-ignored-files-imported-by-source.ts +25 -16
  91. package/src/lib/tasks/shared/load-the-lint-config.ts +14 -12
  92. package/src/lib/tasks/shared/parse-config-files-that-import-from-check.ts +6 -7
  93. package/src/lib/tasks/shared/project-config-and-tool-errors.ts +46 -2
  94. package/src/lib/tasks/shared/provide-project-query-caches.ts +11 -0
  95. package/src/lib/tasks/shared/query-the-typescript-project.ts +108 -43
  96. package/src/lib/tasks/shared/resolve-absolute-paths.ts +4 -1
  97. package/src/lib/tasks/shared/resolve-module-requests.ts +131 -90
  98. package/src/lib/tasks/shared/run-tools-and-decode-their-reports.ts +15 -11
  99. package/src/shared/bans-each-permission-lifts.ts +4 -21
  100. package/src/shared/find-retired-words.ts +1 -1
  101. package/src/shared/lint-rule-messages-and-patterns.ts +7 -12
  102. package/src/shared/record-and-grant-permissions-by-path.ts +41 -65
@@ -1,4 +1,13 @@
1
- import { Array as Arrays, Effect, FileSystem, Path, Predicate, Schema } from "effect";
1
+ import {
2
+ Array as Arrays,
3
+ Context,
4
+ Effect,
5
+ FileSystem,
6
+ Layer,
7
+ Path,
8
+ Predicate,
9
+ Schema,
10
+ } from "effect";
2
11
  import type {
3
12
  CallExpression,
4
13
  Node,
@@ -25,7 +34,7 @@ import {
25
34
  isVariableDeclaration,
26
35
  } from "typescript/unstable/ast/is";
27
36
  import { API, SymbolFlags } from "typescript/unstable/async";
28
- import type { Checker, Program, Symbol as TypeScriptSymbol } from "typescript/unstable/async";
37
+ import type { Checker, Program, Symbol as TypeScriptSymbol, Type } from "typescript/unstable/async";
29
38
 
30
39
  import { isDeclarationFile, isScript, packagePathOf } from "./classify-files-by-role.ts";
31
40
  import { ownedFilesAmong } from "./list-owned-files.ts";
@@ -35,6 +44,7 @@ import {
35
44
  nestedPackageDirectoriesAmong,
36
45
  } from "./list-package-files.ts";
37
46
  import {
47
+ AbsoluteProjectReference,
38
48
  ProgramFilesOutsideProject,
39
49
  ProjectReferencesUndecodable,
40
50
  TypeScriptApiFailed,
@@ -87,6 +97,23 @@ export const typeScriptRequest = <Value>(operation: string, request: () => Promi
87
97
  catch: (cause) => new TypeScriptApiFailed({ operation, reason: String(cause) }),
88
98
  });
89
99
 
100
+ export const typeMembers = (type: Type) =>
101
+ type.isUnionType()
102
+ ? typeScriptRequest("read union members", () => type.getTypes())
103
+ : Effect.succeed([type]);
104
+
105
+ export const callsIn = (sourceFile: SourceFile) => {
106
+ const calls: CallExpression[] = [];
107
+ const visit = (node: Node) => {
108
+ if (isCallExpression(node)) {
109
+ calls.push(node);
110
+ }
111
+ node.forEachChild(visit);
112
+ };
113
+ sourceFile.forEachChild(visit);
114
+ return calls;
115
+ };
116
+
90
117
  export const requiredTypeScriptRequest = <Value>(
91
118
  operation: string,
92
119
  request: () => Promise<Value | undefined>,
@@ -159,6 +186,12 @@ export const projectConfigFiles = (projectFile: string) =>
159
186
  const configFiles = [path.normalize(projectFile)];
160
187
  for (const configFile of configFiles) {
161
188
  for (const reference of yield* referencesOf(configFile)) {
189
+ if (path.isAbsolute(reference.path)) {
190
+ return yield* new AbsoluteProjectReference({
191
+ projectFile: configFile,
192
+ reference: reference.path,
193
+ });
194
+ }
162
195
  const referenced = path.join(path.dirname(configFile), reference.path);
163
196
  const referencedConfigFile = referenced.endsWith(".json")
164
197
  ? referenced
@@ -210,26 +243,6 @@ const parseCompilerOptionsAndInputs = (configFile: string) =>
210
243
  return { effectiveOptions, compilesFiles };
211
244
  }).pipe(Effect.scoped);
212
245
 
213
- const COMPILER_OPTIONS_AND_INPUTS_BY_CONFIG_FILE = new Map<
214
- string,
215
- ReturnType<typeof parseCompilerOptionsAndInputs>
216
- >();
217
-
218
- const compilerOptionsAndInputs = (configFile: string) =>
219
- Effect.gen(function* () {
220
- const cachedParse =
221
- COMPILER_OPTIONS_AND_INPUTS_BY_CONFIG_FILE.get(configFile) ??
222
- (yield* Effect.cached(parseCompilerOptionsAndInputs(configFile)));
223
- COMPILER_OPTIONS_AND_INPUTS_BY_CONFIG_FILE.set(configFile, cachedParse);
224
- return yield* cachedParse;
225
- });
226
-
227
- export const effectiveCompilerOptions = (configFile: string) =>
228
- compilerOptionsAndInputs(configFile).pipe(Effect.map(({ effectiveOptions }) => effectiveOptions));
229
-
230
- export const compilesFiles = (configFile: string) =>
231
- compilerOptionsAndInputs(configFile).pipe(Effect.map((parsed) => parsed.compilesFiles));
232
-
233
246
  export const includedFiles = (projectFile: string) =>
234
247
  Effect.gen(function* () {
235
248
  const path = yield* Path.Path;
@@ -360,16 +373,61 @@ const listProgramFiles = (projectFile: string) =>
360
373
  return { ...compiledFiles, packageSourceFilesOfEachProject };
361
374
  }).pipe(Effect.scoped);
362
375
 
363
- const PROGRAM_FILES_BY_PROJECT = new Map<string, ReturnType<typeof listProgramFiles>>();
376
+ const makeTypeScriptProjectListings = Effect.gen(function* () {
377
+ const services = yield* Effect.context<
378
+ | Effect.Services<ReturnType<typeof listProgramFiles>>
379
+ | Effect.Services<ReturnType<typeof parseCompilerOptionsAndInputs>>
380
+ >();
381
+ const parsedWithTheRunServices = (configFile: string) =>
382
+ parseCompilerOptionsAndInputs(configFile).pipe(Effect.provide(services));
383
+ const listedWithTheRunServices = (projectFile: string) =>
384
+ listProgramFiles(projectFile).pipe(Effect.provide(services));
385
+ const compilerOptionsAndInputsByConfigFile = new Map<
386
+ string,
387
+ ReturnType<typeof parsedWithTheRunServices>
388
+ >();
389
+ const programFilesByProject = new Map<string, ReturnType<typeof listedWithTheRunServices>>();
390
+ return {
391
+ compilerOptionsAndInputs: (configFile: string) =>
392
+ Effect.gen(function* () {
393
+ const cachedParse =
394
+ compilerOptionsAndInputsByConfigFile.get(configFile) ??
395
+ (yield* Effect.cached(parsedWithTheRunServices(configFile)));
396
+ compilerOptionsAndInputsByConfigFile.set(configFile, cachedParse);
397
+ return yield* cachedParse;
398
+ }),
399
+ programFileListing: (projectFile: string) =>
400
+ Effect.gen(function* () {
401
+ const cachedListing =
402
+ programFilesByProject.get(projectFile) ??
403
+ (yield* Effect.cached(listedWithTheRunServices(projectFile)));
404
+ programFilesByProject.set(projectFile, cachedListing);
405
+ return yield* cachedListing;
406
+ }),
407
+ };
408
+ });
409
+
410
+ class TypeScriptProjectListings extends Context.Service<
411
+ TypeScriptProjectListings,
412
+ Effect.Success<typeof makeTypeScriptProjectListings>
413
+ >()("@sshkeda/check/TypeScriptProjectListings") {}
414
+
415
+ export const TypeScriptProjectListingsLive = Layer.effect(
416
+ TypeScriptProjectListings,
417
+ makeTypeScriptProjectListings,
418
+ );
419
+
420
+ const compilerOptionsAndInputs = (configFile: string) =>
421
+ TypeScriptProjectListings.use((listings) => listings.compilerOptionsAndInputs(configFile));
422
+
423
+ export const effectiveCompilerOptions = (configFile: string) =>
424
+ compilerOptionsAndInputs(configFile).pipe(Effect.map(({ effectiveOptions }) => effectiveOptions));
425
+
426
+ export const compilesFiles = (configFile: string) =>
427
+ compilerOptionsAndInputs(configFile).pipe(Effect.map((parsed) => parsed.compilesFiles));
364
428
 
365
429
  const cachedProgramFileListing = (projectFile: string) =>
366
- Effect.gen(function* () {
367
- const cachedListing =
368
- PROGRAM_FILES_BY_PROJECT.get(projectFile) ??
369
- (yield* Effect.cached(listProgramFiles(projectFile)));
370
- PROGRAM_FILES_BY_PROJECT.set(projectFile, cachedListing);
371
- return yield* cachedListing;
372
- });
430
+ TypeScriptProjectListings.use((listings) => listings.programFileListing(projectFile));
373
431
 
374
432
  export const programFiles = (projectFile: string) =>
375
433
  cachedProgramFileListing(projectFile).pipe(Effect.map(({ packageFiles }) => packageFiles));
@@ -572,7 +630,7 @@ export const packageCalleeOf = (
572
630
 
573
631
  const isAnyPackageFile = () => true;
574
632
 
575
- export const packageCalleesIn = (
633
+ const listPackageCalleesIn = (
576
634
  checker: Checker,
577
635
  projectDirectory: string,
578
636
  sourceFile: SourceFile,
@@ -581,21 +639,28 @@ export const packageCalleesIn = (
581
639
  packageCalleeOf(checker, projectDirectory, call, isAnyPackageFile).pipe(
582
640
  Effect.map((callee) => (callee === undefined ? [] : [callee])),
583
641
  );
584
- return Effect.gen(function* () {
585
- const calls: CallExpression[] = [];
586
- const visit = (node: Node) => {
587
- if (isCallExpression(node)) {
588
- calls.push(node);
589
- }
590
- node.forEachChild(visit);
591
- };
592
- sourceFile.forEachChild(visit);
593
- return (yield* Effect.forEach(calls, calleeOf, {
642
+ return Effect.suspend(() =>
643
+ Effect.forEach(callsIn(sourceFile), calleeOf, {
594
644
  concurrency: CONCURRENT_TYPESCRIPT_REQUESTS,
595
- })).flat();
596
- });
645
+ }),
646
+ ).pipe(Effect.map((callees) => callees.flat()));
597
647
  };
598
648
 
649
+ const PACKAGE_CALLEES_BY_FILE = new WeakMap<SourceFile, ReturnType<typeof listPackageCalleesIn>>();
650
+
651
+ export const packageCalleesIn = (
652
+ checker: Checker,
653
+ projectDirectory: string,
654
+ sourceFile: SourceFile,
655
+ ) =>
656
+ Effect.gen(function* () {
657
+ const cachedCallees =
658
+ PACKAGE_CALLEES_BY_FILE.get(sourceFile) ??
659
+ (yield* Effect.cached(listPackageCalleesIn(checker, projectDirectory, sourceFile)));
660
+ PACKAGE_CALLEES_BY_FILE.set(sourceFile, cachedCallees);
661
+ return yield* cachedCallees;
662
+ });
663
+
599
664
  export const openTypeScriptProjects = (
600
665
  projectFile: string,
601
666
  sourceTextOverrides: ReadonlyMap<string, string> = new Map(),
@@ -1,4 +1,7 @@
1
- import { Effect, Path } from "effect";
1
+ import { Effect, FileSystem, Path } from "effect";
2
2
 
3
3
  export const absolutePathOf = (relativePath: string) =>
4
4
  Effect.map(Path.Path, (path) => path.resolve(relativePath));
5
+
6
+ export const realPathOf = (file: string) =>
7
+ FileSystem.FileSystem.use((fileSystem) => fileSystem.realPath(file));
@@ -1,4 +1,5 @@
1
- import { Effect, FileSystem, Option, Path, Result } from "effect";
1
+ import { Context, Effect, FileSystem, Layer, Option, Path, Result } from "effect";
2
+ import type { PlatformError } from "effect";
2
3
 
3
4
  import { moduleResolverFor } from "./create-the-module-resolver.ts";
4
5
  import { withoutQuery } from "./find-module-requests.ts";
@@ -15,18 +16,6 @@ const HASH_THE_RESOLVER_READS_AS_A_CHARACTER = "\0#";
15
16
 
16
17
  const UNNAMED_PACKAGE = { name: null, hasExports: false, realPath: null } as const;
17
18
 
18
- const packagesByDirectory = new Map<
19
- string,
20
- {
21
- readonly name: string | null;
22
- readonly hasExports: boolean;
23
- readonly realPath: string | null;
24
- }
25
- >();
26
-
27
- const realPathOf = (file: string) =>
28
- FileSystem.FileSystem.use((fileSystem) => fileSystem.realPath(file));
29
-
30
19
  const namedManifestAt = (manifestFile: string) =>
31
20
  namedPackageManifestAt(manifestFile).pipe(
32
21
  Effect.map(
@@ -37,85 +26,137 @@ const namedManifestAt = (manifestFile: string) =>
37
26
  ),
38
27
  );
39
28
 
40
- const namedPackageEnclosing = Effect.fn("namedPackageEnclosing")(function* (
41
- directory: string,
42
- projectDirectory: string,
43
- ) {
44
- const key = `${projectDirectory}\0${directory}`;
45
- const known = packagesByDirectory.get(key);
46
- if (known !== undefined) {
47
- return known;
48
- }
49
- const path = yield* Path.Path;
50
- const named = yield* Effect.findFirstFilter(
51
- enclosingPackageManifestsOf(directory, projectDirectory),
52
- namedManifestAt,
53
- );
54
- const identity = Option.isNone(named)
55
- ? UNNAMED_PACKAGE
56
- : {
57
- name: named.value.manifest.name,
58
- hasExports: named.value.manifest.hasExports,
59
- realPath: yield* realPathOf(path.dirname(named.value.manifestFile)),
29
+ const makeModuleResolutions = Effect.sync(() => {
30
+ const packagesByDirectory = new Map<
31
+ string,
32
+ {
33
+ readonly name: string | null;
34
+ readonly hasExports: boolean;
35
+ readonly realPath: string | null;
36
+ }
37
+ >();
38
+
39
+ const realPathsByFile = new Map<string, Effect.Effect<string, PlatformError.PlatformError>>();
40
+
41
+ const realPathOf = (file: string) =>
42
+ Effect.gen(function* () {
43
+ const fileSystem = yield* FileSystem.FileSystem;
44
+ const cachedRealPath =
45
+ realPathsByFile.get(file) ?? (yield* Effect.cached(fileSystem.realPath(file)));
46
+ realPathsByFile.set(file, cachedRealPath);
47
+ return yield* cachedRealPath;
48
+ });
49
+
50
+ const namedPackageEnclosing = (directory: string, projectDirectory: string) =>
51
+ Effect.gen(function* () {
52
+ const key = `${projectDirectory}\0${directory}`;
53
+ const known = packagesByDirectory.get(key);
54
+ if (known !== undefined) {
55
+ return known;
56
+ }
57
+ const path = yield* Path.Path;
58
+ const named = yield* Effect.findFirstFilter(
59
+ enclosingPackageManifestsOf(directory, projectDirectory),
60
+ namedManifestAt,
61
+ );
62
+ const identity = Option.isNone(named)
63
+ ? UNNAMED_PACKAGE
64
+ : {
65
+ name: named.value.manifest.name,
66
+ hasExports: named.value.manifest.hasExports,
67
+ realPath: yield* realPathOf(path.dirname(named.value.manifestFile)),
68
+ };
69
+ packagesByDirectory.set(key, identity);
70
+ return identity;
71
+ });
72
+
73
+ const resolveUncachedModuleRequest = ({
74
+ request,
75
+ importingFile,
76
+ customConditions,
77
+ projectDirectory,
78
+ }: {
79
+ readonly request: string;
80
+ readonly importingFile: string;
81
+ readonly customConditions: readonly string[];
82
+ readonly projectDirectory: string;
83
+ }) =>
84
+ Effect.gen(function* () {
85
+ const path = yield* Path.Path;
86
+ const unresolvable = (reason: string) =>
87
+ new ModuleRequestUnresolvable({ request, importingFile, reason });
88
+ const packageEnclosing = (directory: string) =>
89
+ namedPackageEnclosing(directory, projectDirectory).pipe(
90
+ Effect.catchTags({
91
+ PackageManifestUnreadable: (error) =>
92
+ Effect.fail(
93
+ unresolvable(`${path.relative(projectDirectory, error.location)} ${error.message}`),
94
+ ),
95
+ PlatformError: (error) => Effect.fail(unresolvable(error.message)),
96
+ }),
97
+ );
98
+ const fileRequest = withoutQuery(request);
99
+ const resolverRequest = fileRequest.replaceAll(
100
+ HASH_AFTER_THE_FIRST_CHARACTER,
101
+ HASH_THE_RESOLVER_READS_AS_A_CHARACTER,
102
+ );
103
+ const resolver = yield* moduleResolverFor(customConditions);
104
+ const resolved = yield* Effect.tryPromise({
105
+ try: () => resolver.resolveFileAsync(importingFile, resolverRequest),
106
+ catch: (cause) => unresolvable(String(cause)),
107
+ });
108
+ const resolvedFile = resolved.path;
109
+ if (resolvedFile === undefined) {
110
+ yield* Effect.forEach(
111
+ directoriesAFailedResolutionReads({ importingFile, request: fileRequest }),
112
+ packageEnclosing,
113
+ { discard: true },
114
+ );
115
+ const reason = resolved.error ?? "the resolver returned no file and no error";
116
+ const namesNoFile = resolutionNamesNoFile(resolved, reason);
117
+ if (namesNoFile) {
118
+ return;
119
+ }
120
+ return yield* unresolvable(reason);
121
+ }
122
+ const identity = yield* packageEnclosing(path.dirname(resolvedFile));
123
+ return {
124
+ file: yield* realPathOf(resolvedFile).pipe(
125
+ Effect.mapError((error) => unresolvable(error.message)),
126
+ ),
127
+ packageName: identity.name,
128
+ packageHasExports: identity.hasExports,
129
+ packageRoot: identity.realPath,
60
130
  };
61
- packagesByDirectory.set(key, identity);
62
- return identity;
63
- });
131
+ });
132
+
133
+ const resolutionsByRequest = new Map<string, ReturnType<typeof resolveUncachedModuleRequest>>();
64
134
 
65
- export const resolveModuleRequest = Effect.fn("resolveModuleRequest")(function* ({
66
- request,
67
- importingFile,
68
- customConditions,
69
- projectDirectory,
70
- }: {
71
- readonly request: string;
72
- readonly importingFile: string;
73
- readonly customConditions: readonly string[];
74
- readonly projectDirectory: string;
75
- }) {
76
- const path = yield* Path.Path;
77
- const unresolvable = (reason: string) =>
78
- new ModuleRequestUnresolvable({ request, importingFile, reason });
79
- const packageEnclosing = (directory: string) =>
80
- namedPackageEnclosing(directory, projectDirectory).pipe(
81
- Effect.catchTags({
82
- PackageManifestUnreadable: (error) =>
83
- Effect.fail(
84
- unresolvable(`${path.relative(projectDirectory, error.location)} ${error.message}`),
85
- ),
86
- PlatformError: (error) => Effect.fail(unresolvable(error.message)),
87
- }),
88
- );
89
- const fileRequest = withoutQuery(request);
90
- const resolverRequest = fileRequest.replaceAll(
91
- HASH_AFTER_THE_FIRST_CHARACTER,
92
- HASH_THE_RESOLVER_READS_AS_A_CHARACTER,
93
- );
94
- const resolved = yield* Effect.tryPromise({
95
- try: () => moduleResolverFor(customConditions).resolveFileAsync(importingFile, resolverRequest),
96
- catch: (cause) => unresolvable(String(cause)),
97
- });
98
- const resolvedFile = resolved.path;
99
- if (resolvedFile === undefined) {
100
- yield* Effect.forEach(
101
- directoriesAFailedResolutionReads({ importingFile, request: fileRequest }),
102
- packageEnclosing,
103
- { discard: true },
104
- );
105
- const reason = resolved.error ?? "the resolver returned no file and no error";
106
- const namesNoFile = resolutionNamesNoFile(resolved, reason);
107
- if (namesNoFile) {
108
- return;
109
- }
110
- return yield* unresolvable(reason);
111
- }
112
- const identity = yield* packageEnclosing(path.dirname(resolvedFile));
113
135
  return {
114
- file: yield* realPathOf(resolvedFile).pipe(
115
- Effect.mapError((error) => unresolvable(error.message)),
116
- ),
117
- packageName: identity.name,
118
- packageHasExports: identity.hasExports,
119
- packageRoot: identity.realPath,
136
+ resolveModuleRequest: (resolution: Parameters<typeof resolveUncachedModuleRequest>[0]) =>
137
+ Effect.gen(function* () {
138
+ const key = [
139
+ resolution.projectDirectory,
140
+ resolution.importingFile,
141
+ resolution.request,
142
+ ...resolution.customConditions,
143
+ ].join("\0");
144
+ const cachedResolution =
145
+ resolutionsByRequest.get(key) ??
146
+ (yield* Effect.cached(resolveUncachedModuleRequest(resolution)));
147
+ resolutionsByRequest.set(key, cachedResolution);
148
+ return yield* cachedResolution;
149
+ }),
120
150
  };
121
151
  });
152
+
153
+ class ModuleResolutions extends Context.Service<
154
+ ModuleResolutions,
155
+ Effect.Success<typeof makeModuleResolutions>
156
+ >()("@sshkeda/check/ModuleResolutions") {}
157
+
158
+ export const ModuleResolutionsLive = Layer.effect(ModuleResolutions, makeModuleResolutions);
159
+
160
+ export const resolveModuleRequest = (
161
+ resolution: Parameters<Effect.Success<typeof makeModuleResolutions>["resolveModuleRequest"]>[0],
162
+ ) => ModuleResolutions.use((resolutions) => resolutions.resolveModuleRequest(resolution));
@@ -7,6 +7,7 @@ import { Effect, FileSystem } from "effect";
7
7
  import {
8
8
  ToolExited,
9
9
  ToolNotStarted,
10
+ ToolNotStopped,
10
11
  ToolReportUndecodable,
11
12
  ToolStoppedBySignal,
12
13
  } from "./project-config-and-tool-errors.ts";
@@ -66,21 +67,24 @@ const openedStandardOutputFile = (file: string) =>
66
67
  const stopTheProcessGroupOf = (child: Subprocess) =>
67
68
  Effect.gen(function* () {
68
69
  if (process.platform === WINDOWS) {
69
- yield* Effect.try(() =>
70
- Bun.spawn(["taskkill", "/pid", `${child.pid}`, "/T", "/F"], {
71
- stdin: "ignore",
72
- stdout: "ignore",
73
- stderr: "ignore",
74
- }),
75
- ).pipe(
70
+ yield* Effect.try({
71
+ try: () =>
72
+ Bun.spawn(["taskkill", "/pid", `${child.pid}`, "/T", "/F"], {
73
+ stdin: "ignore",
74
+ stdout: "ignore",
75
+ stderr: "ignore",
76
+ }),
77
+ catch: (cause) => new ToolNotStopped({ command: "taskkill", reason: String(cause) }),
78
+ }).pipe(
76
79
  Effect.flatMap((taskkill) => Effect.promise(() => taskkill.exited)),
77
- Effect.catchTag("UnknownError", () => Effect.void),
80
+ Effect.catchTag("ToolNotStopped", () => Effect.void),
78
81
  );
79
82
  child.kill();
80
83
  } else {
81
- yield* Effect.try(() => process.kill(-child.pid, "SIGKILL")).pipe(
82
- Effect.catchTag("UnknownError", () => Effect.void),
83
- );
84
+ yield* Effect.try({
85
+ try: () => process.kill(-child.pid, "SIGKILL"),
86
+ catch: (cause) => new ToolNotStopped({ command: "kill", reason: String(cause) }),
87
+ }).pipe(Effect.catchTag("ToolNotStopped", () => Effect.void));
84
88
  }
85
89
  yield* Effect.promise(() => child.exited);
86
90
  });
@@ -4,7 +4,6 @@ import {
4
4
  isNodeBuiltinThatBunAliases,
5
5
  nodeBuiltinNameOf,
6
6
  } from "./lint-rule-messages-and-patterns.ts";
7
- import { SCRIPTS_DIRECTORY } from "./test-home-directories.ts";
8
7
 
9
8
  export const SYNC_WRITES = [
10
9
  "appendFileSync",
@@ -112,6 +111,7 @@ export const CREATE_REQUIRE_VALUE_USAGE = "createRequire used other than by a ca
112
111
  export const SCRIPT = "script";
113
112
  export const TRUSTS_UNVERIFIED_TYPES = "trustsUnverifiedTypes";
114
113
  export const WRITES_TO_THE_TERMINAL = "writesToTheTerminal";
114
+ export const READS_CONFIG = "readsConfig";
115
115
  const LOCKS_FILES = "locksFiles";
116
116
  export const HANDLES_EVERY_FAILURE = "handlesEveryFailure";
117
117
 
@@ -235,10 +235,8 @@ const OUTCOME_MEMBERS = [
235
235
  ] as const;
236
236
 
237
237
  const GRANTABLE_BANS = {
238
- readsConfig: {
238
+ [READS_CONFIG]: {
239
239
  ruleName: "no-config-reads",
240
- description:
241
- "Read environment variables, raw command-line arguments and Effect Config only in files allowed readsConfig; no file reads process.argv0, Bun.env, Bun.argv, import.meta.env or parseArgs.",
242
240
  message: `{{usage}} reads configuration`,
243
241
  bans: [
244
242
  globalMembersBan("process", ["env", "argv"]),
@@ -263,8 +261,6 @@ const GRANTABLE_BANS = {
263
261
  },
264
262
  spawnsCommands: {
265
263
  ruleName: "no-command-spawn",
266
- description:
267
- "Start commands only in files allowed spawnsCommands, through Effect ChildProcess, Bun.spawn or spawn from node:child_process; no file uses Bun.spawnSync, Bun.$, the rest of node:child_process or a platform ChildProcessSpawner.",
268
264
  message: "{{usage}} starts a command directly",
269
265
  bans: [
270
266
  moduleBan(["effect/process/ChildProcess", "effect/process/ChildProcessSpawner"]),
@@ -285,8 +281,6 @@ const GRANTABLE_BANS = {
285
281
  },
286
282
  [LOCKS_FILES]: {
287
283
  ruleName: "no-node-file-system",
288
- description:
289
- "Take file locks with open from node:fs/promises and constants from node:fs only in files allowed locksFiles; no file uses the rest of node:fs or node:fs/promises, under any of their names.",
290
284
  message: "{{usage}} reaches the file system directly",
291
285
  bans: [importsBan("node:fs", ["constants"]), importsBan("node:fs/promises", ["open"])],
292
286
  bannedEvenWhenGranted: {
@@ -300,8 +294,6 @@ const GRANTABLE_BANS = {
300
294
  },
301
295
  importsDynamically: {
302
296
  ruleName: "no-dynamic-import",
303
- description:
304
- "Keep the module graph static so tools see every dependency; only files allowed importsDynamically use import() or createRequire, no file loads a module through the require createRequire returns, only resolves one, and no file uses import.meta.require or node:vm.",
305
297
  message: "{{usage}} is banned",
306
298
  bans: [DYNAMIC_IMPORT_BAN, importsBan("node:module", CREATE_REQUIRE_IMPORTS)],
307
299
  bannedEvenWhenGranted: {
@@ -316,14 +308,11 @@ const GRANTABLE_BANS = {
316
308
  },
317
309
  exitsTheProcess: {
318
310
  ruleName: "no-process-exit",
319
- description: "Exit the process directly only in files allowed exitsTheProcess.",
320
311
  message: "{{usage}} exits the process directly",
321
312
  bans: [globalMembersBan("process", ["exit"])],
322
313
  },
323
314
  usesSqlDatabases: {
324
315
  ruleName: "no-sql-clients",
325
- description:
326
- "Talk to SQL databases through Effect SQL only in files allowed usesSqlDatabases; no file uses another SQL client.",
327
316
  message: "{{usage}} uses a SQL client outside a usesSqlDatabases file",
328
317
  bans: [
329
318
  moduleBan(["@effect/sql", "@effect/sql-*", "effect/sql", "effect/sql/*"]),
@@ -350,8 +339,6 @@ const GRANTABLE_BANS = {
350
339
  },
351
340
  [WRITES_TO_THE_TERMINAL]: {
352
341
  ruleName: "no-terminal-writes",
353
- description:
354
- "Write to the terminal through the Effect Stdio service, and use it for more than reading stdin, args or whether a stream is a terminal, only in files allowed writesToTheTerminal; no file uses Effect Console, node:console, process.stdout, process.stderr, Bun.stdout or Bun.stderr.",
355
342
  message: "{{usage}} writes to the terminal",
356
343
  bans: [],
357
344
  bannedEvenWhenGranted: {
@@ -371,8 +358,6 @@ export const PERMISSION_BANS = {
371
358
  ...GRANTABLE_BANS,
372
359
  [TRUSTS_UNVERIFIED_TYPES]: {
373
360
  ruleName: "no-unverified-types",
374
- description:
375
- "Declare a schema from a type guard with Schema.declare or Schema.declareConstructor only in files allowed trustsUnverifiedTypes, whose grant gives a reason.",
376
361
  message: `{{usage}} declares a type nothing verifies`,
377
362
  bans: [
378
363
  effectMembersBan([
@@ -383,8 +368,6 @@ export const PERMISSION_BANS = {
383
368
  },
384
369
  [HANDLES_EVERY_FAILURE]: {
385
370
  ruleName: "no-unnamed-recovery",
386
- description:
387
- "Handle failures by name with catchTag, catchTags or catchReason, and turn a failure you have not named into a success or a value only in files allowed handlesEveryFailure, whose grant gives a reason.",
388
371
  message: "{{usage}} handles failures it does not name",
389
372
  bans: [
390
373
  effectMembersBan(
@@ -399,7 +382,6 @@ export const PERMISSION_BANS = {
399
382
  },
400
383
  syncFileAccess: {
401
384
  ruleName: "no-sync-file-access",
402
- description: "Read and write files without blocking; no file may read or write synchronously.",
403
385
  message: "{{usage}} reaches the file system synchronously",
404
386
  bans: [
405
387
  importsBan(MODULE_PATTERN_WILDCARD, [...SYNC_READS, ...SYNC_WRITES]),
@@ -408,7 +390,6 @@ export const PERMISSION_BANS = {
408
390
  },
409
391
  [SCRIPT]: {
410
392
  ruleName: "no-task-main",
411
- description: `Run tasks with ${TASK_NAMESPACE_EXPORT}.${TASK_MAIN_MEMBER} from ${TASK_PACKAGE} only in files directly in ${SCRIPTS_DIRECTORY}/.`,
412
393
  message: "{{usage}} runs tasks outside a script",
413
394
  bans: [importsBan(TASK_PACKAGE, [`${TASK_NAMESPACE_EXPORT}.${TASK_MAIN_MEMBER}`])],
414
395
  },
@@ -418,6 +399,8 @@ export const PERMISSION_BAN_NAMES = Record.keys(PERMISSION_BANS);
418
399
 
419
400
  export const BANS_NO_GRANT_LIFTS = "onlyThoseNoGrantLifts";
420
401
 
402
+ export const UNUSED_GRANT_REPORTED = "reported";
403
+
421
404
  export const bansNoGrantLifts = (permission: keyof typeof PERMISSION_BANS) => {
422
405
  const entry = PERMISSION_BANS[permission];
423
406
  return "bannedEvenWhenGranted" in entry ? entry.bannedEvenWhenGranted.bans : [];
@@ -1,4 +1,4 @@
1
- export const RETIRED_WORDS: ReadonlySet<string> = new Set([
1
+ const RETIRED_WORDS: ReadonlySet<string> = new Set([
2
2
  "fingerprint",
3
3
  "fingerprints",
4
4
  "folder",