@sshkeda/check 1.0.2 → 2.0.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 (101) hide show
  1. package/README.md +19 -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 +10 -0
  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 +8 -3
  66. package/src/lib/tasks/lib/enforce-file-types/index.ts +6 -1
  67. package/src/lib/tasks/lib/format-with-bun-fmt/internal/declare-the-formatting-task.ts +3 -2
  68. package/src/lib/tasks/lib/judge-index-re-exports/internal/find-index-re-export-violations.ts +27 -21
  69. package/src/lib/tasks/lib/lint-with-oxlint/index.ts +2 -1
  70. package/src/lib/tasks/lib/lint-with-oxlint/internal/check-lint-rules-with-oxlint.ts +11 -8
  71. package/src/lib/tasks/lib/lint-with-oxlint/internal/read-oxlint-json-report.ts +18 -2
  72. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/export-placement-errors.ts +12 -1
  73. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-export-placement-violations.ts +75 -21
  74. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-package-entry-sources.ts +146 -0
  75. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-the-importer-graph.ts +13 -188
  76. package/src/lib/tasks/lib/refuse-disable-directives/index.ts +2 -1
  77. package/src/lib/tasks/lib/refuse-disable-directives/internal/find-disable-directives.ts +9 -3
  78. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/internal/find-error-mappings-to-done.ts +108 -9
  79. package/src/lib/tasks/lib/require-separate-service-layers/internal/find-service-layer-violations.ts +1 -5
  80. package/src/lib/tasks/lib/require-type-checking-every-linted-file/index.ts +2 -1
  81. package/src/lib/tasks/lib/require-type-checking-every-linted-file/internal/find-linted-files-not-type-checked.ts +2 -4
  82. package/src/lib/tasks/shared/check-each-nested-package.ts +13 -1
  83. package/src/lib/tasks/shared/classify-files-by-role.ts +5 -0
  84. package/src/lib/tasks/shared/count-the-line-of-an-offset.ts +20 -2
  85. package/src/lib/tasks/shared/create-the-module-resolver.ts +39 -23
  86. package/src/lib/tasks/shared/declare-lint-config-task.ts +2 -1
  87. package/src/lib/tasks/shared/declare-typescript-config-task.ts +30 -2
  88. package/src/lib/tasks/shared/find-unmet-typescript-config-requirements.ts +24 -7
  89. package/src/lib/tasks/shared/list-ignored-files-imported-by-source.ts +25 -16
  90. package/src/lib/tasks/shared/load-the-lint-config.ts +14 -12
  91. package/src/lib/tasks/shared/parse-config-files-that-import-from-check.ts +6 -7
  92. package/src/lib/tasks/shared/project-config-and-tool-errors.ts +63 -4
  93. package/src/lib/tasks/shared/provide-project-query-caches.ts +11 -0
  94. package/src/lib/tasks/shared/query-the-typescript-project.ts +108 -43
  95. package/src/lib/tasks/shared/resolve-absolute-paths.ts +4 -1
  96. package/src/lib/tasks/shared/resolve-module-requests.ts +131 -90
  97. package/src/lib/tasks/shared/run-tools-and-decode-their-reports.ts +15 -11
  98. package/src/shared/bans-each-permission-lifts.ts +4 -21
  99. package/src/shared/find-retired-words.ts +1 -1
  100. package/src/shared/lint-rule-messages-and-patterns.ts +7 -12
  101. package/src/shared/record-and-grant-permissions-by-path.ts +41 -65
@@ -0,0 +1,146 @@
1
+ import { Effect, FileSystem, Path, Schema } from "effect";
2
+
3
+ import { isTypeScriptSourceFile } from "../../../shared/classify-files-by-role.ts";
4
+ import { PACKAGE_MANIFEST_FILE } from "../../../shared/find-named-package-manifests.ts";
5
+ import { existingPackageFiles } from "../../../shared/list-package-files.ts";
6
+ import {
7
+ PackageExportsMixKeys,
8
+ PackageManifestFieldInvalid,
9
+ } from "../../../shared/project-config-and-tool-errors.ts";
10
+ import { JSON_OBJECT } from "../../../shared/read-package-manifest-object.ts";
11
+
12
+ const PACKAGE_PATTERN_WILDCARD = "*";
13
+ const PARTS_AROUND_ONE_WILDCARD = 2;
14
+
15
+ const PACKAGE_ENTRIES = Schema.fromJsonString(
16
+ Schema.Struct({
17
+ main: Schema.optionalKey(Schema.String),
18
+ module: Schema.optionalKey(Schema.String),
19
+ types: Schema.optionalKey(Schema.String),
20
+ typings: Schema.optionalKey(Schema.String),
21
+ exports: Schema.optionalKey(Schema.Json),
22
+ }),
23
+ );
24
+
25
+ const stringsIn = (value: Schema.Json): readonly string[] => {
26
+ if (typeof value === "string") {
27
+ return [value];
28
+ }
29
+ if (Array.isArray(value)) {
30
+ return value.flatMap((item: Schema.Json) => stringsIn(item));
31
+ }
32
+ return Schema.is(JSON_OBJECT)(value)
33
+ ? Object.values(value).flatMap((item) => stringsIn(item))
34
+ : [];
35
+ };
36
+ const capturingPattern = (entry: string) =>
37
+ new RegExp(
38
+ `^${entry
39
+ .split(PACKAGE_PATTERN_WILDCARD)
40
+ .map((part) => RegExp.escape(part))
41
+ .join("(.+)")}$`,
42
+ "u",
43
+ );
44
+
45
+ const packageEntryMatch = (entry: string) => {
46
+ const pattern = capturingPattern(entry);
47
+ return (path: string) => (isTypeScriptSourceFile(path) ? pattern.exec(path) : null);
48
+ };
49
+
50
+ const exportsSubpathEntries = (exportsField: Schema.Json) => {
51
+ const isSingleExportTarget =
52
+ exportsField === null || typeof exportsField !== "object" || Array.isArray(exportsField);
53
+ if (isSingleExportTarget) {
54
+ return [[".", exportsField] as const];
55
+ }
56
+ const keys = Object.keys(exportsField);
57
+ const subpathKeys = keys.filter((key) => key.startsWith("."));
58
+ if (subpathKeys.length === 0) {
59
+ return [[".", exportsField] as const];
60
+ }
61
+ return subpathKeys.length === keys.length ? Object.entries(exportsField) : undefined;
62
+ };
63
+
64
+ const subpathMatcher = (subpathPattern: string) =>
65
+ new RegExp(
66
+ `^${subpathPattern
67
+ .split(PACKAGE_PATTERN_WILDCARD)
68
+ .map((part) => RegExp.escape(part))
69
+ .join(".+")}$`,
70
+ "u",
71
+ );
72
+
73
+ const patternPrefixLength = (key: string) => key.indexOf(PACKAGE_PATTERN_WILDCARD);
74
+
75
+ const isSubpathPattern = (key: string) =>
76
+ key.split(PACKAGE_PATTERN_WILDCARD).length === PARTS_AROUND_ONE_WILDCARD;
77
+
78
+ const subpathKeyFor = (keys: readonly string[], subpath: string) => {
79
+ if (keys.includes(subpath)) {
80
+ return subpath;
81
+ }
82
+ return keys
83
+ .filter((key) => isSubpathPattern(key) && subpathMatcher(key).test(subpath))
84
+ .toSorted(
85
+ (first, second) =>
86
+ patternPrefixLength(second) - patternPrefixLength(first) || second.length - first.length,
87
+ )[0];
88
+ };
89
+
90
+ export const packageEntrySourcesAmong = (packageDirectory: string, paths: readonly string[]) =>
91
+ Effect.gen(function* () {
92
+ const fileSystem = yield* FileSystem.FileSystem;
93
+ const path = yield* Path.Path;
94
+ const manifestFile = path.join(packageDirectory, PACKAGE_MANIFEST_FILE);
95
+ const listed = yield* existingPackageFiles(packageDirectory, [PACKAGE_MANIFEST_FILE]);
96
+ const decodedManifest = (text: string) =>
97
+ Schema.decodeEffect(PACKAGE_ENTRIES)(text).pipe(
98
+ Effect.mapError(
99
+ (error) => new PackageManifestFieldInvalid({ path: manifestFile, reason: error.message }),
100
+ ),
101
+ );
102
+ const manifest = listed.includes(PACKAGE_MANIFEST_FILE)
103
+ ? yield* fileSystem.readFileString(manifestFile).pipe(Effect.flatMap(decodedManifest))
104
+ : {};
105
+ const sourcesOfEntry = (entry: string) => {
106
+ const matchOf = packageEntryMatch(path.normalize(entry).split(path.sep).join("/"));
107
+ return paths.flatMap((file) => {
108
+ const matched = matchOf(file);
109
+ return matched === null ? [] : [{ file, capture: matched[1] }];
110
+ });
111
+ };
112
+ const manifestEntries = [manifest.main, manifest.module, manifest.types, manifest.typings]
113
+ .filter((entry) => entry !== undefined)
114
+ .filter((entry) => isTypeScriptSourceFile(entry));
115
+ const subpaths = manifest.exports === undefined ? [] : exportsSubpathEntries(manifest.exports);
116
+ if (subpaths === undefined) {
117
+ return yield* new PackageExportsMixKeys({ path: manifestFile });
118
+ }
119
+ const subpathKeys = subpaths.map(([subpath]) => subpath);
120
+ return [
121
+ ...manifestEntries.map((entry) => {
122
+ const sources = sourcesOfEntry(entry).map(({ file }) => file);
123
+ return { entry, sources, started: sources };
124
+ }),
125
+ ...subpaths.flatMap(([subpath, target]) =>
126
+ stringsIn(target)
127
+ .filter((entry) => isTypeScriptSourceFile(entry))
128
+ .map((entry) => {
129
+ const matched = sourcesOfEntry(entry);
130
+ return {
131
+ entry,
132
+ sources: matched.map(({ file }) => file),
133
+ started: matched
134
+ .filter(({ capture }) => {
135
+ const exposed =
136
+ capture === undefined
137
+ ? subpath
138
+ : subpath.replace(PACKAGE_PATTERN_WILDCARD, capture);
139
+ return subpathKeyFor(subpathKeys, exposed) === subpath;
140
+ })
141
+ .map(({ file }) => file),
142
+ };
143
+ }),
144
+ ),
145
+ ];
146
+ });
@@ -3,7 +3,6 @@ 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
6
  import {
8
7
  isDeclarationFile,
9
8
  isTopLevelScript,
@@ -13,16 +12,13 @@ import {
13
12
  moduleDirectoriesAmong,
14
13
  packagePathOf,
15
14
  } from "../../../shared/classify-files-by-role.ts";
16
- import { lineNumberAt } from "../../../shared/count-the-line-of-an-offset.ts";
15
+ import { lineNumbersIn, lineOfTheFirstLabel } from "../../../shared/count-the-line-of-an-offset.ts";
17
16
  import { moduleRequestsIn, URL_REQUESTS } from "../../../shared/find-module-requests.ts";
18
17
  import type { MODULE_REQUEST_KINDS } from "../../../shared/find-module-requests.ts";
19
- import { PACKAGE_MANIFEST_FILE } from "../../../shared/find-named-package-manifests.ts";
20
18
  import { existingPackageFiles } from "../../../shared/list-package-files.ts";
21
19
  import { isFormatConfigTextRefusedIn } from "../../../shared/parse-config-files-that-import-from-check.ts";
22
20
  import {
23
21
  BunConfigInvalid,
24
- PackageExportsMixKeys,
25
- PackageManifestFieldInvalid,
26
22
  SourceFileUnparsable,
27
23
  } from "../../../shared/project-config-and-tool-errors.ts";
28
24
  import type { ModuleRequestUnresolvable } from "../../../shared/project-config-and-tool-errors.ts";
@@ -31,48 +27,18 @@ import {
31
27
  CUSTOM_CONDITIONS,
32
28
  effectiveCompilerOptions,
33
29
  } from "../../../shared/query-the-typescript-project.ts";
34
- import { JSON_OBJECT } from "../../../shared/read-package-manifest-object.ts";
35
30
  import { resolveModuleRequest } from "../../../shared/resolve-module-requests.ts";
36
31
  import { ImportUnresolvableInTheImportBoundaryCheck } from "./export-placement-errors.ts";
32
+ import { packageEntrySourcesAmong } from "./find-package-entry-sources.ts";
37
33
 
38
34
  export const EVERY_EXPORT = "*";
39
35
  export const DEFAULT_EXPORT = "default";
40
- const SOURCE_EXTENSION = /(?:\.d)?\.[cm]?[jt]sx?$/u;
41
- const TYPESCRIPT_PROJECT_PATTERN = "tsconfig*.json";
42
- const TYPESCRIPT_PROJECT_FILE_NAME = /^tsconfig(?:\.[\w-]+)?\.json$/u;
43
- const BUILD_DIRECTORIES = Schema.Struct({
44
- outDir: Schema.optionalKey(Schema.String),
45
- rootDir: Schema.optionalKey(Schema.String),
46
- });
47
36
  const BUN_CONFIG_FILE = "bunfig.toml";
48
37
  const PRELOADS = Schema.optionalKey(Schema.Union([Schema.String, Schema.Array(Schema.String)]));
49
38
  const BUN_CONFIG = Schema.Struct({
50
39
  preload: PRELOADS,
51
40
  test: Schema.optionalKey(Schema.Struct({ preload: PRELOADS })),
52
41
  });
53
- const PACKAGE_PATTERN_WILDCARD = "*";
54
- const PARTS_AROUND_ONE_WILDCARD = 2;
55
-
56
- const PACKAGE_ENTRIES = Schema.fromJsonString(
57
- Schema.Struct({
58
- main: Schema.optionalKey(Schema.String),
59
- module: Schema.optionalKey(Schema.String),
60
- exports: Schema.optionalKey(Schema.Json),
61
- }),
62
- );
63
-
64
- const stringsIn = (value: Schema.Json): readonly string[] => {
65
- if (typeof value === "string") {
66
- return [value];
67
- }
68
- if (Array.isArray(value)) {
69
- return value.flatMap((item: Schema.Json) => stringsIn(item));
70
- }
71
- return Schema.is(JSON_OBJECT)(value)
72
- ? Object.values(value).flatMap((item) => stringsIn(item))
73
- : [];
74
- };
75
-
76
42
  const importedNameOf = (importName: {
77
43
  readonly kind: `${ImportNameKind}`;
78
44
  readonly name: string | null;
@@ -106,7 +72,7 @@ const moduleUsesIn = (
106
72
  ) => Effect.Effect<
107
73
  string | undefined,
108
74
  ModuleRequestUnresolvable,
109
- FileSystem.FileSystem | Path.Path
75
+ Effect.Services<ReturnType<typeof resolveModuleRequest>>
110
76
  >,
111
77
  ) =>
112
78
  Effect.gen(function* () {
@@ -114,9 +80,14 @@ const moduleUsesIn = (
114
80
  if (parsed.errors.length > 0) {
115
81
  return yield* new SourceFileUnparsable({
116
82
  file: path,
83
+ ...lineOfTheFirstLabel(
84
+ text,
85
+ parsed.errors.flatMap((error) => error.labels),
86
+ ),
117
87
  reason: parsed.errors.map((error) => error.message).join("; "),
118
88
  });
119
89
  }
90
+ const lineAt = lineNumbersIn(text);
120
91
  const uses: {
121
92
  readonly file: string;
122
93
  readonly names: readonly string[];
@@ -133,7 +104,7 @@ const moduleUsesIn = (
133
104
  uses.push({
134
105
  file,
135
106
  names: declaration.entries.map((entry) => importedNameOf(entry.importName)),
136
- line: lineNumberAt(text, declaration.start),
107
+ line: lineAt(declaration.start),
137
108
  kind: importsOnlyTypes ? "type" : "static",
138
109
  });
139
110
  }
@@ -152,7 +123,7 @@ const moduleUsesIn = (
152
123
  ? (entry.importName.name ?? DEFAULT_EXPORT)
153
124
  : EVERY_EXPORT,
154
125
  ],
155
- line: lineNumberAt(text, entry.start),
126
+ line: lineAt(entry.start),
156
127
  kind: entry.isType ? "type" : "static",
157
128
  });
158
129
  }
@@ -175,7 +146,7 @@ const moduleUsesIn = (
175
146
  uses.push({
176
147
  file,
177
148
  names: request.kind === "launch" ? [] : [request.namedExport ?? EVERY_EXPORT],
178
- line: lineNumberAt(text, request.start),
149
+ line: lineAt(request.start),
179
150
  kind: request.kind,
180
151
  });
181
152
  }
@@ -183,68 +154,6 @@ const moduleUsesIn = (
183
154
  return { uses, parsed, text };
184
155
  });
185
156
 
186
- const withoutExtension = (path: string) => path.replace(SOURCE_EXTENSION, "");
187
-
188
- const capturingPattern = (entry: string) =>
189
- new RegExp(
190
- `^${withoutExtension(entry)
191
- .split(PACKAGE_PATTERN_WILDCARD)
192
- .map((part) => RegExp.escape(part))
193
- .join("(.+)")}$`,
194
- "u",
195
- );
196
-
197
- const packageEntryMatches = (entries: readonly string[]) => {
198
- const patterns = entries.map((entry) => capturingPattern(entry));
199
- return (path: string) =>
200
- SOURCE_EXTENSION.test(path)
201
- ? patterns.flatMap((pattern) => {
202
- const matched = pattern.exec(withoutExtension(path));
203
- return matched === null ? [] : [{ capture: matched[1] }];
204
- })
205
- : [];
206
- };
207
-
208
- const exportsSubpathEntries = (exportsField: Schema.Json) => {
209
- const isSingleExportTarget =
210
- exportsField === null || typeof exportsField !== "object" || Array.isArray(exportsField);
211
- if (isSingleExportTarget) {
212
- return [[".", exportsField] as const];
213
- }
214
- const keys = Object.keys(exportsField);
215
- const subpathKeys = keys.filter((key) => key.startsWith("."));
216
- if (subpathKeys.length === 0) {
217
- return [[".", exportsField] as const];
218
- }
219
- return subpathKeys.length === keys.length ? Object.entries(exportsField) : undefined;
220
- };
221
-
222
- const subpathMatcher = (subpathPattern: string) =>
223
- new RegExp(
224
- `^${subpathPattern
225
- .split(PACKAGE_PATTERN_WILDCARD)
226
- .map((part) => RegExp.escape(part))
227
- .join(".+")}$`,
228
- "u",
229
- );
230
-
231
- const patternPrefixLength = (key: string) => key.indexOf(PACKAGE_PATTERN_WILDCARD);
232
-
233
- const isSubpathPattern = (key: string) =>
234
- key.split(PACKAGE_PATTERN_WILDCARD).length === PARTS_AROUND_ONE_WILDCARD;
235
-
236
- const subpathKeyFor = (keys: readonly string[], subpath: string) => {
237
- if (keys.includes(subpath)) {
238
- return subpath;
239
- }
240
- return keys
241
- .filter((key) => isSubpathPattern(key) && subpathMatcher(key).test(subpath))
242
- .toSorted(
243
- (first, second) =>
244
- patternPrefixLength(second) - patternPrefixLength(first) || second.length - first.length,
245
- )[0];
246
- };
247
-
248
157
  export const findTheImporterGraph = (projectFile: string) =>
249
158
  Effect.gen(function* () {
250
159
  const fileSystem = yield* FileSystem.FileSystem;
@@ -280,97 +189,13 @@ export const findTheImporterGraph = (projectFile: string) =>
280
189
  }
281
190
 
282
191
  const trackedPackageFiles = new Set(
283
- yield* existingPackageFiles(packageDirectory, [
284
- PACKAGE_MANIFEST_FILE,
285
- BUN_CONFIG_FILE,
286
- TYPESCRIPT_PROJECT_PATTERN,
287
- ]),
192
+ yield* existingPackageFiles(packageDirectory, [BUN_CONFIG_FILE]),
288
193
  );
289
194
  const readTrackedFile = (name: string) =>
290
195
  trackedPackageFiles.has(name)
291
196
  ? fileSystem.readFileString(path.join(packageDirectory, name)).pipe(Effect.asSome)
292
197
  : Effect.succeedNone;
293
- const manifestText = yield* readTrackedFile(PACKAGE_MANIFEST_FILE);
294
- const manifest = Option.isNone(manifestText)
295
- ? {}
296
- : yield* Schema.decodeEffect(PACKAGE_ENTRIES)(manifestText.value).pipe(
297
- Effect.mapError(
298
- (error) =>
299
- new PackageManifestFieldInvalid({
300
- path: path.join(packageDirectory, PACKAGE_MANIFEST_FILE),
301
- reason: error.message,
302
- }),
303
- ),
304
- );
305
- const buildDirectories = yield* Effect.forEach(
306
- [...trackedPackageFiles].filter((name) => TYPESCRIPT_PROJECT_FILE_NAME.test(name)),
307
- (name) =>
308
- effectiveCompilerOptions(path.join(packageDirectory, name)).pipe(
309
- Effect.flatMap(Schema.decodeUnknownEffect(BUILD_DIRECTORIES)),
310
- Effect.map((options) =>
311
- options.outDir === undefined
312
- ? []
313
- : [{ outDirectory: options.outDir, rootDirectory: options.rootDir ?? "" }],
314
- ),
315
- ),
316
- );
317
- const sourcesOfEntry = (entry: string) => {
318
- const normalized = path.normalize(entry).split(path.sep).join("/");
319
- const mapped = buildDirectories
320
- .flat()
321
- .flatMap(({ outDirectory, rootDirectory }) =>
322
- isWithin(normalized, outDirectory)
323
- ? [
324
- path
325
- .join(rootDirectory, path.relative(outDirectory, normalized))
326
- .split(path.sep)
327
- .join("/"),
328
- ]
329
- : [],
330
- );
331
- const matchesOf = packageEntryMatches([normalized, ...mapped]);
332
- return paths.flatMap((file) =>
333
- matchesOf(file)
334
- .slice(0, 1)
335
- .map(({ capture }) => ({ file, capture })),
336
- );
337
- };
338
- const manifestEntries = [manifest.main, manifest.module]
339
- .filter((entry) => entry !== undefined)
340
- .filter((entry) => SOURCE_EXTENSION.test(entry));
341
- const subpaths = manifest.exports === undefined ? [] : exportsSubpathEntries(manifest.exports);
342
- if (subpaths === undefined) {
343
- return yield* new PackageExportsMixKeys({
344
- path: path.join(packageDirectory, PACKAGE_MANIFEST_FILE),
345
- });
346
- }
347
- const subpathKeys = subpaths.map(([subpath]) => subpath);
348
- const entrySources = [
349
- ...manifestEntries.map((entry) => {
350
- const sources = sourcesOfEntry(entry).map(({ file }) => file);
351
- return { entry, sources, started: sources };
352
- }),
353
- ...subpaths.flatMap(([subpath, target]) =>
354
- stringsIn(target)
355
- .filter((entry) => SOURCE_EXTENSION.test(entry))
356
- .map((entry) => {
357
- const matched = sourcesOfEntry(entry);
358
- return {
359
- entry,
360
- sources: matched.map(({ file }) => file),
361
- started: matched
362
- .filter(({ capture }) => {
363
- const exposed =
364
- capture === undefined
365
- ? subpath
366
- : subpath.replace(PACKAGE_PATTERN_WILDCARD, capture);
367
- return subpathKeyFor(subpathKeys, exposed) === subpath;
368
- })
369
- .map(({ file }) => file),
370
- };
371
- }),
372
- ),
373
- ];
198
+ const entrySources = yield* packageEntrySourcesAmong(packageDirectory, paths);
374
199
  const bunConfig = yield* readTrackedFile(BUN_CONFIG_FILE);
375
200
  const bunConfigPath = path.join(packageDirectory, BUN_CONFIG_FILE);
376
201
  const bunOptions = Option.isNone(bunConfig)
@@ -4,6 +4,7 @@ import { Effect } from "effect";
4
4
  import { inEachPackage } from "../../shared/check-each-nested-package.ts";
5
5
  import { lintConfigFile } from "../../shared/declare-lint-config-task.ts";
6
6
  import { typeScriptConfig } from "../../shared/declare-typescript-config-task.ts";
7
+ import { ProjectQueryCachesLive } from "../../shared/provide-project-query-caches.ts";
7
8
  import { findDisableDirectivesInLintedFilesOf } from "./internal/find-disable-directives.ts";
8
9
 
9
10
  export const directives = Task.make(
@@ -11,5 +12,5 @@ export const directives = Task.make(
11
12
  Effect.andThen(
12
13
  Task.all([typeScriptConfig, lintConfigFile]),
13
14
  inEachPackage("directives", ".", findDisableDirectivesInLintedFilesOf),
14
- ),
15
+ ).pipe(Effect.provide(ProjectQueryCachesLive)),
15
16
  );
@@ -3,7 +3,7 @@ import { parseSync } from "oxc-parser";
3
3
 
4
4
  import { FORMAT_CONFIG_FILE } from "../../../../../shared/config-file-names.ts";
5
5
  import { isDirective } from "../../../../../shared/lint-rule-messages-and-patterns.ts";
6
- import { lineNumberAt } from "../../../shared/count-the-line-of-an-offset.ts";
6
+ import { lineNumbersIn, lineOfTheFirstLabel } from "../../../shared/count-the-line-of-an-offset.ts";
7
7
  import { lintedFiles } from "../../../shared/list-linted-files.ts";
8
8
  import { isFormatConfigTextRefusedIn } from "../../../shared/parse-config-files-that-import-from-check.ts";
9
9
  import { quietViolations } from "../../../shared/print-failures-and-keep-detail-in-the-trace.ts";
@@ -25,16 +25,22 @@ export const disableDirectivesIn = (file: string, directory = ".") =>
25
25
  const parsed = parseSync(file, text);
26
26
  if (parsed.errors.length > 0) {
27
27
  return parsed.errors.map(
28
- (error) => new SourceFileUnparsable({ file, reason: error.message }),
28
+ (error) =>
29
+ new SourceFileUnparsable({
30
+ file,
31
+ ...lineOfTheFirstLabel(text, error.labels),
32
+ reason: error.message,
33
+ }),
29
34
  );
30
35
  }
36
+ const lineAt = lineNumbersIn(text);
31
37
  return parsed.comments
32
38
  .filter((comment) => isDirective(comment.value))
33
39
  .map(
34
40
  (comment) =>
35
41
  new DisableDirective({
36
42
  file,
37
- line: lineNumberAt(text, comment.start),
43
+ line: lineAt(comment.start),
38
44
  directive: comment.value.trim(),
39
45
  }),
40
46
  );
@@ -1,6 +1,7 @@
1
1
  import { Effect, Path } from "effect";
2
2
  import type { Cause } from "effect";
3
3
  import type { SourceFile } from "typescript/unstable/ast";
4
+ import { isArrayLiteralExpression, isStringLiteralLikeNode } from "typescript/unstable/ast/is";
4
5
  import { SignatureKind } from "typescript/unstable/async";
5
6
  import type { Checker, Type } from "typescript/unstable/async";
6
7
 
@@ -9,6 +10,7 @@ import {
9
10
  nodePosition,
10
11
  packageCalleesIn,
11
12
  requiredTypeScriptRequest,
13
+ typeMembers,
12
14
  typeScriptRequest,
13
15
  } from "../../../shared/query-the-typescript-project.ts";
14
16
  import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
@@ -19,6 +21,10 @@ const DONE_TYPE_ID = "~effect/Cause/Done" satisfies keyof Cause.Done;
19
21
  const FAILURE_HANDLER = "onFailure";
20
22
  const ERROR_MAPPINGS = new Set(["mapError", "mapErrorEager"]);
21
23
  const BOTH_MAPPINGS = new Set(["mapBoth", "mapBothEager"]);
24
+ const RECOVERY_PREFIX = "catch";
25
+ const RESERVED_WORD_SUFFIX = /_$/u;
26
+ const FAILING_TYPE_IDS = ["~effect/Effect", "~effect/Stream"] as const;
27
+ const FAILURE_VARIANCE = "_E";
22
28
  const MODULE_OF_DECLARATION_FILE = new Map([
23
29
  ["effect/dist/effect.d.ts", "Effect"],
24
30
  ["effect/dist/stream.d.ts", "Stream"],
@@ -26,11 +32,6 @@ const MODULE_OF_DECLARATION_FILE = new Map([
26
32
  ["effect/dist/sink.d.ts", "Sink"],
27
33
  ]);
28
34
 
29
- const typeMembers = (type: Type) =>
30
- type.isUnionType()
31
- ? typeScriptRequest("read union members", () => type.getTypes())
32
- : Effect.succeed([type]);
33
-
34
35
  const canBeDone = (checker: Checker, type: Type) =>
35
36
  typeMembers(type).pipe(
36
37
  Effect.flatMap((members) =>
@@ -56,6 +57,80 @@ const returnsDone = (checker: Checker, mapping: Type) =>
56
57
  return returned.some(Boolean);
57
58
  });
58
59
 
60
+ const returnedTypesOf = (checker: Checker, callable: Type) =>
61
+ Effect.gen(function* () {
62
+ const signatures = yield* typeScriptRequest("read the handler's signatures", () =>
63
+ checker.getSignaturesOfType(callable, SignatureKind.Call),
64
+ );
65
+ return yield* Effect.forEach(signatures, (signature) =>
66
+ requiredTypeScriptRequest("read the handler's return type", () =>
67
+ checker.getReturnTypeOfSignature(signature),
68
+ ),
69
+ );
70
+ });
71
+
72
+ const failureTypesOf = (checker: Checker, failing: Type) =>
73
+ Effect.gen(function* () {
74
+ const variances = yield* Effect.forEach(FAILING_TYPE_IDS, (typeId) =>
75
+ typeScriptRequest("read the variance of a failing type", () =>
76
+ checker.getPropertyOfType(failing, typeId),
77
+ ),
78
+ );
79
+ const failures = yield* Effect.forEach(
80
+ variances.filter((variance) => variance !== undefined),
81
+ (variance) =>
82
+ Effect.gen(function* () {
83
+ const varianceType = yield* requiredTypeScriptRequest("read a variance's type", () =>
84
+ checker.getTypeOfSymbol(variance),
85
+ );
86
+ const failure = yield* typeScriptRequest("read the failure variance", () =>
87
+ checker.getPropertyOfType(varianceType, FAILURE_VARIANCE),
88
+ );
89
+ if (failure === undefined) {
90
+ return [];
91
+ }
92
+ const failureType = yield* requiredTypeScriptRequest("read the failure type", () =>
93
+ checker.getTypeOfSymbol(failure),
94
+ );
95
+ return yield* returnedTypesOf(checker, failureType);
96
+ }),
97
+ );
98
+ return failures.flat();
99
+ });
100
+
101
+ const recoveryCanFailWithDone = (checker: Checker, handler: Type) =>
102
+ Effect.gen(function* () {
103
+ const recovered = (yield* returnedTypesOf(checker, handler)).map((returned) =>
104
+ typeMembers(returned),
105
+ );
106
+ const failing = (yield* Effect.all(recovered)).flat();
107
+ const failures = (yield* Effect.forEach(failing, (type) =>
108
+ failureTypesOf(checker, type),
109
+ )).flat();
110
+ const doneFailures = yield* Effect.forEach(failures, (failure) => canBeDone(checker, failure));
111
+ return doneFailures.some(Boolean);
112
+ });
113
+
114
+ const handlersIn = (checker: Checker, argument: Type) =>
115
+ Effect.gen(function* () {
116
+ const properties = yield* typeScriptRequest("read the handlers of an object", () =>
117
+ checker.getPropertiesOfType(argument),
118
+ );
119
+ const handlers = yield* Effect.forEach(properties, (property) =>
120
+ typeScriptRequest("read a handler's type", () => checker.getTypeOfSymbol(property)),
121
+ );
122
+ return [argument, ...handlers.filter((handler) => handler !== undefined)];
123
+ });
124
+
125
+ const recoveryFailsWithDone = (checker: Checker, argument: Type) =>
126
+ Effect.gen(function* () {
127
+ const handlers = yield* handlersIn(checker, argument);
128
+ const failsWithDone = yield* Effect.forEach(handlers, (handler) =>
129
+ recoveryCanFailWithDone(checker, handler),
130
+ );
131
+ return failsWithDone.some(Boolean);
132
+ });
133
+
59
134
  const failureMappingOf = (checker: Checker, argument: Type, name: string) =>
60
135
  Effect.gen(function* () {
61
136
  if (!BOTH_MAPPINGS.has(name)) {
@@ -81,23 +156,47 @@ const fileViolations = (
81
156
  const callees = yield* packageCalleesIn(checker, projectDirectory, sourceFile);
82
157
  const mappings = callees.flatMap(({ call, file, name }) => {
83
158
  const moduleName = MODULE_OF_DECLARATION_FILE.get(file);
84
- const isMapping = ERROR_MAPPINGS.has(name) || BOTH_MAPPINGS.has(name);
159
+ const isRecovery = name.startsWith(RECOVERY_PREFIX);
160
+ const isMapping = ERROR_MAPPINGS.has(name) || BOTH_MAPPINGS.has(name) || isRecovery;
85
161
  const mapping = call.arguments.at(-1);
86
162
  const isEffectMapping = moduleName !== undefined && isMapping && mapping !== undefined;
87
- return isEffectMapping ? [{ call, mapping, name, operation: `${moduleName}.${name}` }] : [];
163
+ const handlers = isRecovery
164
+ ? call.arguments.filter(
165
+ (argument) => !isStringLiteralLikeNode(argument) && !isArrayLiteralExpression(argument),
166
+ )
167
+ : [];
168
+ return isEffectMapping
169
+ ? [
170
+ {
171
+ call,
172
+ mapping,
173
+ handlers,
174
+ name,
175
+ operation: `${moduleName}.${name.replace(RESERVED_WORD_SUFFIX, "")}`,
176
+ },
177
+ ]
178
+ : [];
88
179
  });
89
180
  const violations = yield* Effect.forEach(
90
181
  mappings,
91
- ({ call, mapping, name, operation }) =>
182
+ ({ call, mapping, handlers, name, operation }) =>
92
183
  Effect.gen(function* () {
93
184
  const argument = yield* typeScriptRequest("read the mapping's type", () =>
94
185
  checker.getTypeAtLocation(mapping),
95
186
  );
187
+ const handlerTypes = yield* typeScriptRequest("read the recovery handlers' types", () =>
188
+ checker.getTypeAtLocation(handlers),
189
+ );
96
190
  const failureMapping =
97
191
  argument === undefined ? undefined : yield* failureMappingOf(checker, argument, name);
98
192
  const mapsToDone =
99
193
  failureMapping !== undefined && (yield* returnsDone(checker, failureMapping));
100
- if (!mapsToDone) {
194
+ const recoveries = yield* Effect.forEach(
195
+ handlerTypes.filter((handler) => handler !== undefined),
196
+ (handler) => recoveryFailsWithDone(checker, handler),
197
+ );
198
+ const endsStreams = mapsToDone || recoveries.some(Boolean);
199
+ if (!endsStreams) {
101
200
  return [];
102
201
  }
103
202
  const { line, column } = nodePosition(sourceFile, call);
@@ -21,6 +21,7 @@ import {
21
21
  nodePosition,
22
22
  requiredTypeScriptRequest,
23
23
  resolvedSymbols,
24
+ typeMembers,
24
25
  typeScriptRequest,
25
26
  } from "../../../shared/query-the-typescript-project.ts";
26
27
  import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
@@ -35,11 +36,6 @@ const LAYER_ASSIGNMENTS = new Set([
35
36
  SyntaxKind.AmpersandAmpersandEqualsToken,
36
37
  ]);
37
38
 
38
- const typeMembers = (type: Type) =>
39
- type.isUnionType()
40
- ? typeScriptRequest("read union members", () => type.getTypes())
41
- : Effect.succeed([type]);
42
-
43
39
  const hasTypeProperty = (checker: Checker, type: Type, name: string) =>
44
40
  typeScriptRequest("read a service layer property", () =>
45
41
  checker.getPropertyOfType(type, name),