@sshkeda/check 0.0.0-stage → 1.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 (167) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +156 -2
  3. package/docs/how-to-make-check-pass.md +71 -0
  4. package/package.json +51 -4
  5. package/src/index.ts +8 -0
  6. package/src/internal/ban-abbreviated-words-in-declared-names.ts +165 -0
  7. package/src/internal/ban-checked-members-outside-calls.ts +151 -0
  8. package/src/internal/ban-comments.ts +23 -0
  9. package/src/internal/ban-comparing-or-switching-on-tag.ts +114 -0
  10. package/src/internal/ban-deadlines-inside-tests.ts +41 -0
  11. package/src/internal/ban-declared-values.ts +70 -0
  12. package/src/internal/ban-dropped-failures-detached-fibers-sleeps-and-untraced-functions.ts +67 -0
  13. package/src/internal/ban-failures-collected-as-results.ts +57 -0
  14. package/src/internal/ban-fallbacks-of-named-recoveries.ts +118 -0
  15. package/src/internal/ban-function-overloads.ts +107 -0
  16. package/src/internal/ban-global-error-in-failure-types.ts +146 -0
  17. package/src/internal/ban-instanceof-in-effect-recovery-callbacks.ts +63 -0
  18. package/src/internal/ban-let-and-effect-mutable-ref.ts +79 -0
  19. package/src/internal/ban-logic-in-index-files.ts +178 -0
  20. package/src/internal/ban-namespaces-used-without-a-member.ts +176 -0
  21. package/src/internal/ban-node-builtins-that-effect-replaces.ts +42 -0
  22. package/src/internal/ban-parsing-outside-data-without-a-schema.ts +299 -0
  23. package/src/internal/ban-re-exports.ts +172 -0
  24. package/src/internal/ban-reading-the-clock-and-sleeping-outside-effect.ts +239 -0
  25. package/src/internal/ban-retired-words-in-names.ts +49 -0
  26. package/src/internal/ban-scanning-directories-with-bun-glob.ts +79 -0
  27. package/src/internal/ban-shebang-lines.ts +26 -0
  28. package/src/internal/ban-timer-globals-and-the-global-object.ts +34 -0
  29. package/src/internal/ban-timer-schedules-without-deadlines.ts +240 -0
  30. package/src/internal/ban-type-and-interface-declarations.ts +48 -0
  31. package/src/internal/ban-type-predicates.ts +82 -0
  32. package/src/internal/ban-unknown-in-function-signatures.ts +143 -0
  33. package/src/internal/ban-vague-error-class-names.ts +28 -0
  34. package/src/internal/ban-vague-file-names.ts +51 -0
  35. package/src/internal/ban-what-a-file-is-not-granted.ts +512 -0
  36. package/src/internal/ban-while-do-while-and-for-loops.ts +27 -0
  37. package/src/internal/confine-service-declarations-to-granted-files.ts +116 -0
  38. package/src/internal/confine-the-stdio-service-to-terminal-output.ts +190 -0
  39. package/src/internal/define-the-lint-plugin-and-configs.ts +361 -0
  40. package/src/internal/describe-and-decode-rule-options.ts +22 -0
  41. package/src/internal/keep-assertions-in-the-test-home-and-ban-test-runners.ts +128 -0
  42. package/src/internal/keep-effect-testing-helpers-in-test-files.ts +157 -0
  43. package/src/internal/match-banned-modules-and-globals.ts +71 -0
  44. package/src/internal/match-effect-service-factories.ts +20 -0
  45. package/src/internal/require-a-named-const-for-compound-conditions.ts +44 -0
  46. package/src/internal/require-capital-snake-case-and-as-const-on-literal-constants.ts +141 -0
  47. package/src/internal/require-service-keys-to-end-with-their-class-name.ts +64 -0
  48. package/src/internal/resolve-what-an-expression-imports.ts +295 -0
  49. package/src/internal/sort-type-constituents.ts +82 -0
  50. package/src/internal/split-names-into-words.ts +12 -0
  51. package/src/internal/visit-every-declared-name.ts +264 -0
  52. package/src/lib/tasks/index.ts +1 -0
  53. package/src/lib/tasks/internal/declare-the-check-task.ts +29 -0
  54. package/src/lib/tasks/internal/declare-the-checker-queries-task.ts +41 -0
  55. package/src/lib/tasks/internal/declare-the-typed-checks-task.ts +25 -0
  56. package/src/lib/tasks/internal/run-checks-over-one-typescript-project.ts +68 -0
  57. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/index.ts +15 -0
  58. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/internal/check-effect-diagnostics-with-effect-tsgo.ts +211 -0
  59. package/src/lib/tasks/lib/check-effect-diagnostics-with-effect-tsgo/internal/read-effect-tsgo-json-report.ts +39 -0
  60. package/src/lib/tasks/lib/check-import-boundaries/index.ts +1 -0
  61. package/src/lib/tasks/lib/check-import-boundaries/internal/find-import-boundary-violations.ts +415 -0
  62. package/src/lib/tasks/lib/check-import-boundaries/internal/find-subpath-import-targets.ts +117 -0
  63. package/src/lib/tasks/lib/check-import-boundaries/internal/find-what-hides-an-import.ts +65 -0
  64. package/src/lib/tasks/lib/check-import-boundaries/internal/import-boundary-errors.ts +176 -0
  65. package/src/lib/tasks/lib/check-uses-by-their-declarations/index.ts +1 -0
  66. package/src/lib/tasks/lib/check-uses-by-their-declarations/internal/declared-use-errors.ts +32 -0
  67. package/src/lib/tasks/lib/check-uses-by-their-declarations/internal/find-declared-use-violations.ts +38 -0
  68. package/src/lib/tasks/lib/check-uses-by-their-declarations/internal/find-sync-calls.ts +23 -0
  69. package/src/lib/tasks/lib/check-uses-by-their-declarations/internal/find-type-only-schemas.ts +375 -0
  70. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/index.ts +1 -0
  71. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/find-layer-provides-outside-program-starts.ts +648 -0
  72. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/layer-provide-errors.ts +27 -0
  73. package/src/lib/tasks/lib/confine-layer-provides-to-program-starts/internal/resolve-imported-package-apis.ts +262 -0
  74. package/src/lib/tasks/lib/confine-stdio-to-granted-files/index.ts +1 -0
  75. package/src/lib/tasks/lib/confine-stdio-to-granted-files/internal/find-ungranted-stdio-uses.ts +219 -0
  76. package/src/lib/tasks/lib/confine-stdio-to-granted-files/internal/stdio-use-errors.ts +31 -0
  77. package/src/lib/tasks/lib/detect-inferrable-annotations/index.ts +1 -0
  78. package/src/lib/tasks/lib/detect-inferrable-annotations/internal/find-inferrable-annotations.ts +357 -0
  79. package/src/lib/tasks/lib/detect-inferrable-annotations/internal/inferrable-annotation-errors.ts +33 -0
  80. package/src/lib/tasks/lib/detect-repeated-service-yields/index.ts +1 -0
  81. package/src/lib/tasks/lib/detect-repeated-service-yields/internal/find-repeated-service-yields.ts +162 -0
  82. package/src/lib/tasks/lib/detect-repeated-service-yields/internal/repeated-service-yield-errors.ts +25 -0
  83. package/src/lib/tasks/lib/enforce-file-layout/index.ts +5 -0
  84. package/src/lib/tasks/lib/enforce-file-layout/internal/check-the-layout-of-each-package.ts +9 -0
  85. package/src/lib/tasks/lib/enforce-file-layout/internal/file-layout-errors.ts +417 -0
  86. package/src/lib/tasks/lib/enforce-file-layout/internal/find-export-path-mismatches.ts +83 -0
  87. package/src/lib/tasks/lib/enforce-file-layout/internal/find-file-layout-violations.ts +827 -0
  88. package/src/lib/tasks/lib/enforce-file-layout/internal/find-module-layout-violations.ts +82 -0
  89. package/src/lib/tasks/lib/enforce-file-layout/internal/resolve-task-imports.ts +178 -0
  90. package/src/lib/tasks/lib/enforce-file-types/index.ts +5 -0
  91. package/src/lib/tasks/lib/enforce-file-types/internal/file-type-errors.ts +21 -0
  92. package/src/lib/tasks/lib/enforce-file-types/internal/find-file-type-violations.ts +78 -0
  93. package/src/lib/tasks/lib/format-with-bun-fmt/index.ts +1 -0
  94. package/src/lib/tasks/lib/format-with-bun-fmt/internal/check-formatting-with-bun-fmt.ts +157 -0
  95. package/src/lib/tasks/lib/format-with-bun-fmt/internal/declare-the-formatting-task.ts +66 -0
  96. package/src/lib/tasks/lib/format-with-bun-fmt/internal/find-format-config-violations.ts +16 -0
  97. package/src/lib/tasks/lib/format-with-bun-fmt/internal/find-format-input-violations.ts +74 -0
  98. package/src/lib/tasks/lib/format-with-bun-fmt/internal/find-symbolic-links.ts +14 -0
  99. package/src/lib/tasks/lib/format-with-bun-fmt/internal/unformatted-file-errors.ts +12 -0
  100. package/src/lib/tasks/lib/judge-index-re-exports/index.ts +1 -0
  101. package/src/lib/tasks/lib/judge-index-re-exports/internal/find-index-re-export-violations.ts +353 -0
  102. package/src/lib/tasks/lib/judge-index-re-exports/internal/index-re-export-errors.ts +21 -0
  103. package/src/lib/tasks/lib/lint-with-oxlint/index.ts +15 -0
  104. package/src/lib/tasks/lib/lint-with-oxlint/internal/check-lint-rules-with-oxlint.ts +123 -0
  105. package/src/lib/tasks/lib/lint-with-oxlint/internal/check-unsafe-enum-assignments.ts +152 -0
  106. package/src/lib/tasks/lib/lint-with-oxlint/internal/find-tsgolint-executable.ts +21 -0
  107. package/src/lib/tasks/lib/lint-with-oxlint/internal/read-oxlint-json-report.ts +82 -0
  108. package/src/lib/tasks/lib/lint-with-oxlint/internal/read-tsgolint-rule-messages.ts +68 -0
  109. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/index.ts +1 -0
  110. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/export-placement-errors.ts +135 -0
  111. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-export-placement-violations.ts +507 -0
  112. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-misplaced-files.ts +116 -0
  113. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-subdivided-directories.ts +29 -0
  114. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/find-the-importer-graph.ts +451 -0
  115. package/src/lib/tasks/lib/place-exports-in-the-narrowest-directory/internal/list-binding-names.ts +49 -0
  116. package/src/lib/tasks/lib/refuse-disable-directives/index.ts +15 -0
  117. package/src/lib/tasks/lib/refuse-disable-directives/internal/disable-directive-errors.ts +45 -0
  118. package/src/lib/tasks/lib/refuse-disable-directives/internal/find-disable-directives.ts +66 -0
  119. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/index.ts +1 -0
  120. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/internal/error-mapping-errors.ts +21 -0
  121. package/src/lib/tasks/lib/refuse-error-mappings-that-end-streams/internal/find-error-mappings-to-done.ts +135 -0
  122. package/src/lib/tasks/lib/require-separate-service-layers/index.ts +1 -0
  123. package/src/lib/tasks/lib/require-separate-service-layers/internal/find-service-layer-violations.ts +170 -0
  124. package/src/lib/tasks/lib/require-separate-service-layers/internal/service-layer-errors.ts +21 -0
  125. package/src/lib/tasks/lib/require-type-checking-every-linted-file/index.ts +14 -0
  126. package/src/lib/tasks/lib/require-type-checking-every-linted-file/internal/find-linted-files-not-type-checked.ts +117 -0
  127. package/src/lib/tasks/lib/require-type-checking-every-linted-file/internal/linted-file-errors.ts +51 -0
  128. package/src/lib/tasks/lib/type-check-with-bun-check/index.ts +11 -0
  129. package/src/lib/tasks/lib/type-check-with-bun-check/internal/check-types-with-bun-check.ts +54 -0
  130. package/src/lib/tasks/lib/type-check-with-bun-check/internal/read-bun-check-output.ts +73 -0
  131. package/src/lib/tasks/lib/type-check-with-bun-check/internal/type-check-errors.ts +10 -0
  132. package/src/lib/tasks/shared/check-each-nested-package.ts +79 -0
  133. package/src/lib/tasks/shared/classify-files-by-role.ts +115 -0
  134. package/src/lib/tasks/shared/count-the-line-of-an-offset.ts +2 -0
  135. package/src/lib/tasks/shared/create-the-module-resolver.ts +38 -0
  136. package/src/lib/tasks/shared/declare-lint-config-task.ts +13 -0
  137. package/src/lib/tasks/shared/declare-typescript-config-task.ts +18 -0
  138. package/src/lib/tasks/shared/encode-compact-json.ts +5 -0
  139. package/src/lib/tasks/shared/find-installed-package-binaries.ts +62 -0
  140. package/src/lib/tasks/shared/find-module-requests.ts +482 -0
  141. package/src/lib/tasks/shared/find-named-package-manifests.ts +94 -0
  142. package/src/lib/tasks/shared/find-unmet-typescript-config-requirements.ts +60 -0
  143. package/src/lib/tasks/shared/list-ignored-files-imported-by-source.ts +79 -0
  144. package/src/lib/tasks/shared/list-linted-files.ts +28 -0
  145. package/src/lib/tasks/shared/list-owned-files.ts +13 -0
  146. package/src/lib/tasks/shared/list-package-files.ts +66 -0
  147. package/src/lib/tasks/shared/load-the-lint-config.ts +176 -0
  148. package/src/lib/tasks/shared/match-granted-patch-files.ts +88 -0
  149. package/src/lib/tasks/shared/parse-config-files-that-import-from-check.ts +310 -0
  150. package/src/lib/tasks/shared/print-failures-and-keep-detail-in-the-trace.ts +99 -0
  151. package/src/lib/tasks/shared/project-config-and-tool-errors.ts +485 -0
  152. package/src/lib/tasks/shared/query-the-typescript-project.ts +635 -0
  153. package/src/lib/tasks/shared/read-named-package-manifests.ts +53 -0
  154. package/src/lib/tasks/shared/read-package-manifest-object.ts +28 -0
  155. package/src/lib/tasks/shared/resolve-absolute-paths.ts +4 -0
  156. package/src/lib/tasks/shared/resolve-module-requests.ts +121 -0
  157. package/src/lib/tasks/shared/run-tools-and-decode-their-reports.ts +98 -0
  158. package/src/lib/tasks/shared/tool-file-locations.ts +38 -0
  159. package/src/shared/bans-each-permission-lifts.ts +454 -0
  160. package/src/shared/config-file-names.ts +3 -0
  161. package/src/shared/find-retired-words.ts +17 -0
  162. package/src/shared/format-reported-failures.ts +31 -0
  163. package/src/shared/lint-rule-messages-and-patterns.ts +104 -0
  164. package/src/shared/match-file-names-and-path-prefixes.ts +18 -0
  165. package/src/shared/permission-grant-errors.ts +42 -0
  166. package/src/shared/record-and-grant-permissions-by-path.ts +419 -0
  167. package/src/shared/test-home-directories.ts +4 -0
@@ -0,0 +1,507 @@
1
+ import { Effect, Option, Path } from "effect";
2
+ import { Visitor } from "oxc-parser";
3
+ import type {
4
+ ParseResult,
5
+ Directive,
6
+ ArrowFunctionExpression,
7
+ Function as FunctionNode,
8
+ JSXElementName,
9
+ JSXIdentifier,
10
+ JSXNamespacedName,
11
+ Statement,
12
+ } from "oxc-parser";
13
+
14
+ import { isWithin } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
15
+ import { SCRIPTS_DIRECTORY } from "../../../../../shared/test-home-directories.ts";
16
+ import {
17
+ isTopLevelScript,
18
+ isDeclarationFile,
19
+ isTestEntryFile,
20
+ isUnderTestDirectory,
21
+ } from "../../../shared/classify-files-by-role.ts";
22
+ import { lineNumberAt } from "../../../shared/count-the-line-of-an-offset.ts";
23
+ import { ownedFilesAmong } from "../../../shared/list-owned-files.ts";
24
+ import { projectSymbolsIn } from "../../../shared/query-the-typescript-project.ts";
25
+ import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
26
+ import { absolutePathOf } from "../../../shared/resolve-absolute-paths.ts";
27
+ import {
28
+ ExportPlacementViolations,
29
+ PackageEntryWithoutSource,
30
+ TestNotRun,
31
+ TestOnlyExport,
32
+ UnusedExport,
33
+ } from "./export-placement-errors.ts";
34
+ import { findMisplacedFiles } from "./find-misplaced-files.ts";
35
+ import { DEFAULT_EXPORT, EVERY_EXPORT, findTheImporterGraph } from "./find-the-importer-graph.ts";
36
+ import { bindingNamesOf, parameterNamesOf } from "./list-binding-names.ts";
37
+
38
+ const UNRESOLVABLE_IMPORTS_ARE_REPORTED_BY_THE_IMPORT_BOUNDARY_CHECK = Effect.succeedNone;
39
+
40
+ const rootOfJsxName = (name: JSXElementName): JSXIdentifier | JSXNamespacedName =>
41
+ name.type === "JSXMemberExpression" ? rootOfJsxName(name.object) : name;
42
+
43
+ const declaredNamesOf = (statement: Directive | Statement): readonly string[] => {
44
+ const declaration =
45
+ statement.type === "ExportNamedDeclaration" ? statement.declaration : statement;
46
+ if (declaration === null) {
47
+ return [];
48
+ }
49
+ if (declaration.type === "VariableDeclaration") {
50
+ return declaration.declarations.flatMap((declarator) => bindingNamesOf(declarator.id));
51
+ }
52
+ const declaresNamedBinding =
53
+ declaration.type === "FunctionDeclaration" ||
54
+ declaration.type === "ClassDeclaration" ||
55
+ declaration.type === "TSDeclareFunction";
56
+ if (declaresNamedBinding) {
57
+ return declaration.id === null ? [] : [declaration.id.name];
58
+ }
59
+ if (declaration.type !== "ExportDefaultDeclaration") {
60
+ return [];
61
+ }
62
+ const defaultExported = declaration.declaration;
63
+ const isDefaultFunctionOrClass =
64
+ defaultExported.type === "FunctionDeclaration" || defaultExported.type === "ClassDeclaration";
65
+ if (!isDefaultFunctionOrClass) {
66
+ return [];
67
+ }
68
+ return defaultExported.id === null ? [] : [defaultExported.id.name];
69
+ };
70
+
71
+ const parsedFile = (
72
+ parsed: ParseResult,
73
+ text: string,
74
+ symbolIdsAt: ReturnType<ReturnType<typeof projectSymbolsIn>>,
75
+ ) =>
76
+ Effect.gen(function* () {
77
+ const body = parsed.program.body;
78
+ const statementAt = (offset: number) =>
79
+ body.findIndex((statement) => statement.start <= offset && offset < statement.end);
80
+ const statementOfLocal = new Map(
81
+ [...body.entries()].flatMap(([index, statement]) =>
82
+ declaredNamesOf(statement).map((name) => [name, index] as const),
83
+ ),
84
+ );
85
+ const exportedStatement = (
86
+ entry: (typeof parsed.module.staticExports)[number]["entries"][number],
87
+ ) =>
88
+ entry.localName.name === null
89
+ ? statementAt(entry.start)
90
+ : statementOfLocal.get(entry.localName.name);
91
+ const exports = new Map<
92
+ string,
93
+ { statement: ReturnType<typeof exportedStatement>; line: number }
94
+ >();
95
+ const localNameOfExport = new Map<string, string>();
96
+ const exportsOfStatement = new Map<number, string[]>();
97
+ for (const declaration of parsed.module.staticExports) {
98
+ for (const entry of declaration.entries) {
99
+ const exportedName =
100
+ entry.exportName.kind === "Default" ? DEFAULT_EXPORT : entry.exportName.name;
101
+ const localName = entry.localName.name;
102
+ if (exportedName === null) {
103
+ continue;
104
+ }
105
+ const statement = exportedStatement(entry);
106
+ exports.set(exportedName, { statement, line: lineNumberAt(text, entry.start) });
107
+ if (localName !== null) {
108
+ localNameOfExport.set(exportedName, localName);
109
+ }
110
+ if (statement !== undefined) {
111
+ exportsOfStatement.set(statement, [
112
+ ...(exportsOfStatement.get(statement) ?? []),
113
+ exportedName,
114
+ ]);
115
+ }
116
+ }
117
+ }
118
+ const identifiers: { name: string; start: number }[] = [];
119
+ const shorthandStarts = new Set<number>();
120
+ const notReferences = new Set<number>();
121
+ const skippedRanges: { start: number; end: number }[] = [];
122
+ const scopes: {
123
+ readonly start: number;
124
+ readonly end: number;
125
+ readonly names: Set<string>;
126
+ }[] = [];
127
+ const declarations: {
128
+ readonly start: number;
129
+ readonly names: readonly string[];
130
+ }[] = [];
131
+ const addScope = (
132
+ node: { readonly start: number; readonly end: number },
133
+ names: readonly string[],
134
+ ) => scopes.push({ start: node.start, end: node.end, names: new Set(names) });
135
+ const functionScope = (node: ArrowFunctionExpression | FunctionNode) =>
136
+ addScope(node, node.params.flatMap(parameterNamesOf));
137
+ new Visitor({
138
+ Identifier(node) {
139
+ identifiers.push({ name: node.name, start: node.start });
140
+ },
141
+ MemberExpression(node) {
142
+ if (!node.computed) {
143
+ notReferences.add(node.property.start);
144
+ }
145
+ },
146
+ JSXOpeningElement(node) {
147
+ const rootName = rootOfJsxName(node.name);
148
+ if (rootName.type === "JSXIdentifier") {
149
+ identifiers.push({ name: rootName.name, start: rootName.start });
150
+ }
151
+ },
152
+ Property(node) {
153
+ if (!node.computed) {
154
+ if (node.shorthand) {
155
+ shorthandStarts.add(node.value.start);
156
+ } else {
157
+ notReferences.add(node.key.start);
158
+ }
159
+ }
160
+ },
161
+ MethodDefinition(node) {
162
+ if (!node.computed) {
163
+ notReferences.add(node.key.start);
164
+ }
165
+ },
166
+ PropertyDefinition(node) {
167
+ if (!node.computed) {
168
+ notReferences.add(node.key.start);
169
+ }
170
+ },
171
+ TSPropertySignature(node) {
172
+ if (!node.computed) {
173
+ notReferences.add(node.key.start);
174
+ }
175
+ },
176
+ TSMethodSignature(node) {
177
+ if (!node.computed) {
178
+ notReferences.add(node.key.start);
179
+ }
180
+ },
181
+ TSQualifiedName(node) {
182
+ notReferences.add(node.right.start);
183
+ },
184
+ ImportDeclaration(node) {
185
+ skippedRanges.push(node);
186
+ },
187
+ ExportNamedDeclaration(node) {
188
+ if (node.declaration === null) {
189
+ skippedRanges.push(node);
190
+ }
191
+ },
192
+ FunctionDeclaration(node) {
193
+ functionScope(node);
194
+ declarations.push({
195
+ start: node.start,
196
+ names: node.id === null ? [] : [node.id.name],
197
+ });
198
+ },
199
+ FunctionExpression(node) {
200
+ functionScope(node);
201
+ if (node.id !== null) {
202
+ addScope(node, [node.id.name]);
203
+ }
204
+ },
205
+ ArrowFunctionExpression(node) {
206
+ functionScope(node);
207
+ },
208
+ ClassDeclaration(node) {
209
+ declarations.push({
210
+ start: node.start,
211
+ names: node.id === null ? [] : [node.id.name],
212
+ });
213
+ },
214
+ ClassExpression(node) {
215
+ if (node.id !== null) {
216
+ addScope(node, [node.id.name]);
217
+ }
218
+ },
219
+ CatchClause(node) {
220
+ addScope(node, bindingNamesOf(node.param));
221
+ },
222
+ BlockStatement(node) {
223
+ addScope(node, []);
224
+ },
225
+ StaticBlock(node) {
226
+ addScope(node, []);
227
+ },
228
+ SwitchStatement(node) {
229
+ addScope(node, []);
230
+ },
231
+ ForStatement(node) {
232
+ addScope(node, []);
233
+ },
234
+ ForInStatement(node) {
235
+ addScope(node, []);
236
+ },
237
+ ForOfStatement(node) {
238
+ addScope(node, []);
239
+ },
240
+ VariableDeclaration(node) {
241
+ declarations.push({
242
+ start: node.start,
243
+ names: node.declarations.flatMap((declarator) => bindingNamesOf(declarator.id)),
244
+ });
245
+ },
246
+ }).visit(parsed.program);
247
+ const innermostScopeOf = (offset: number) =>
248
+ scopes
249
+ .filter((scope) => scope.start < offset && offset < scope.end)
250
+ .toSorted((first, second) => second.start - first.start)[0];
251
+ for (const declaration of declarations) {
252
+ const scope = innermostScopeOf(declaration.start);
253
+ if (scope === undefined) {
254
+ continue;
255
+ }
256
+ for (const name of declaration.names) {
257
+ scope.names.add(name);
258
+ }
259
+ }
260
+ const isShadowed = (name: string, offset: number) =>
261
+ scopes.some((scope) => scope.start <= offset && offset < scope.end && scope.names.has(name));
262
+ const referencesByStatement = body.map(() => new Set<string>());
263
+ const candidates = identifiers.filter(
264
+ (identifier) =>
265
+ !notReferences.has(identifier.start) &&
266
+ !skippedRanges.some(
267
+ (range) => range.start <= identifier.start && identifier.start < range.end,
268
+ ),
269
+ );
270
+ if (symbolIdsAt === undefined) {
271
+ for (const identifier of candidates) {
272
+ if (!isShadowed(identifier.name, identifier.start)) {
273
+ referencesByStatement[statementAt(identifier.start)]?.add(identifier.name);
274
+ }
275
+ }
276
+ } else {
277
+ const exportedLocals = new Set(localNameOfExport.values());
278
+ const declarationOf = new Map(
279
+ [...exportedLocals].flatMap((name) => {
280
+ const declaring = statementOfLocal.get(name);
281
+ const declared = candidates.find(
282
+ (identifier) => identifier.name === name && statementAt(identifier.start) === declaring,
283
+ );
284
+ return declared === undefined ? [] : [[name, declared.start] as const];
285
+ }),
286
+ );
287
+ const referencing = candidates.filter((identifier) => exportedLocals.has(identifier.name));
288
+ const ids = yield* symbolIdsAt([
289
+ ...[...declarationOf].map(([name, start]) => ({
290
+ start,
291
+ end: start + name.length,
292
+ shorthand: false,
293
+ })),
294
+ ...referencing.map((identifier) => ({
295
+ start: identifier.start,
296
+ end: identifier.start + identifier.name.length,
297
+ shorthand: shorthandStarts.has(identifier.start),
298
+ })),
299
+ ]);
300
+ const declaredIds = new Map(
301
+ [...declarationOf.keys()].map((name, index) => [name, ids[index]?.id] as const),
302
+ );
303
+ for (const [index, identifier] of referencing.entries()) {
304
+ const id = ids[declarationOf.size + index]?.id;
305
+ const refersToTheTopLevelDeclaration =
306
+ id !== undefined && id === declaredIds.get(identifier.name);
307
+ if (refersToTheTopLevelDeclaration) {
308
+ referencesByStatement[statementAt(identifier.start)]?.add(identifier.name);
309
+ }
310
+ }
311
+ }
312
+ return {
313
+ exports,
314
+ referencesByStatement,
315
+ localNameOfExport,
316
+ exportsOfStatement,
317
+ };
318
+ });
319
+
320
+ export const findExportPlacementViolations = <Failure, Requirements>(
321
+ projectFile: string,
322
+ openedProjects: Effect.Effect<
323
+ Effect.Success<ReturnType<typeof openTypeScriptProjects>>,
324
+ Failure,
325
+ Requirements
326
+ >,
327
+ ) =>
328
+ Effect.gen(function* () {
329
+ const opened = yield* openedProjects;
330
+ const resolvedGraph = yield* findTheImporterGraph(projectFile).pipe(
331
+ Effect.asSome,
332
+ Effect.catchTag(
333
+ "ImportUnresolvableInTheImportBoundaryCheck",
334
+ () => UNRESOLVABLE_IMPORTS_ARE_REPORTED_BY_THE_IMPORT_BOUNDARY_CHECK,
335
+ ),
336
+ );
337
+ if (Option.isNone(resolvedGraph)) {
338
+ return;
339
+ }
340
+ const graph = resolvedGraph.value;
341
+ const {
342
+ paths,
343
+ entrySources,
344
+ reach,
345
+ exportsAreReadFromOutside,
346
+ roots,
347
+ reachable,
348
+ moduleDirectories,
349
+ } = graph;
350
+ const projectDirectory = (yield* Path.Path).dirname(yield* absolutePathOf(projectFile));
351
+ const ownedPaths = yield* ownedFilesAmong(projectDirectory, paths);
352
+ const owned = new Set(ownedPaths);
353
+ const symbolIdsIn = projectSymbolsIn(projectDirectory, opened);
354
+ const files = new Map(
355
+ yield* Effect.forEach(graph.files, ([file, uses]) =>
356
+ parsedFile(uses.parsed, uses.text, symbolIdsIn(file)).pipe(
357
+ Effect.map((parsed) => [file, { ...parsed, ...uses }] as const),
358
+ ),
359
+ ),
360
+ );
361
+ const runByScripts = reach(
362
+ paths.filter((path) => isTopLevelScript(path)),
363
+ (use) => use.kind !== "type",
364
+ );
365
+
366
+ const users = new Map<string, Map<string, Set<string>>>();
367
+ const usersOf = (file: string, name: string) => {
368
+ const byName = users.get(file) ?? new Map<string, Set<string>>();
369
+ users.set(file, byName);
370
+ const found = byName.get(name) ?? new Set<string>();
371
+ byName.set(name, found);
372
+ return found;
373
+ };
374
+ const exportedNamesOf = (file: string): ReadonlySet<string> =>
375
+ new Set(files.get(file)?.exports.keys());
376
+ const everyExportUsers = new Map<string, Set<string>>();
377
+ const everyExportUsersOf = (file: string) => {
378
+ const found = everyExportUsers.get(file) ?? new Set<string>();
379
+ everyExportUsers.set(file, found);
380
+ return found;
381
+ };
382
+ const markUse = (file: string, name: string, user: string) => {
383
+ if (name === EVERY_EXPORT) {
384
+ everyExportUsersOf(file).add(user);
385
+ } else {
386
+ usersOf(file, name).add(user);
387
+ }
388
+ };
389
+ for (const [file, parsed] of files) {
390
+ for (const use of parsed.uses) {
391
+ for (const name of use.names) {
392
+ markUse(use.file, name, file);
393
+ }
394
+ }
395
+ }
396
+ for (const root of roots) {
397
+ markUse(root, EVERY_EXPORT, root);
398
+ }
399
+ const allUsersOf = (file: string, name: string): ReadonlySet<string> => {
400
+ const named = users.get(file)?.get(name);
401
+ const everyUser = exportedNamesOf(file).has(name) ? everyExportUsers.get(file) : undefined;
402
+ if (everyUser === undefined) {
403
+ return named ?? new Set();
404
+ }
405
+ return named === undefined ? everyUser : new Set([...named, ...everyUser]);
406
+ };
407
+
408
+ for (const [file, parsed] of files) {
409
+ const inherits: { readonly from: string; readonly to: string }[] = [];
410
+ for (const [name, exported] of parsed.exports) {
411
+ const localName = parsed.localNameOfExport.get(name);
412
+ if (localName === undefined) {
413
+ continue;
414
+ }
415
+ for (const [index, references] of parsed.referencesByStatement.entries()) {
416
+ const isReferencedFromAnotherStatement =
417
+ exported.statement !== index && references.has(localName);
418
+ if (!isReferencedFromAnotherStatement) {
419
+ continue;
420
+ }
421
+ const exportingNames = (parsed.exportsOfStatement.get(index) ?? []).filter(
422
+ (exportingName) => exportingName !== name,
423
+ );
424
+ if (exportingNames.length === 0) {
425
+ usersOf(file, name).add(file);
426
+ }
427
+ for (const from of exportingNames) {
428
+ inherits.push({ from, to: name });
429
+ }
430
+ }
431
+ }
432
+ const inheritUsersUntilStable = () => {
433
+ const inheritChanges = inherits.map(({ from, to }) => {
434
+ const target = usersOf(file, to);
435
+ const addedUsers = [...allUsersOf(file, from)].filter((user) => !target.has(user));
436
+ for (const user of addedUsers) {
437
+ target.add(user);
438
+ }
439
+ return addedUsers.length > 0;
440
+ });
441
+ if (inheritChanges.includes(true)) {
442
+ inheritUsersUntilStable();
443
+ }
444
+ };
445
+ inheritUsersUntilStable();
446
+ }
447
+
448
+ const exportViolations: (TestOnlyExport | UnusedExport)[] = [];
449
+ for (const [file, parsed] of files) {
450
+ const isExemptFromExportChecks =
451
+ !owned.has(file) ||
452
+ isUnderTestDirectory(file) ||
453
+ exportsAreReadFromOutside(file) ||
454
+ isDeclarationFile(file);
455
+ if (isExemptFromExportChecks) {
456
+ continue;
457
+ }
458
+ for (const [name, { line }] of parsed.exports) {
459
+ const location = `${file}:${line}`;
460
+ const recordedUsers = [...allUsersOf(file, name)];
461
+ const everyUser = recordedUsers.filter((user) => reachable.has(user));
462
+ const [unreachableUser] = recordedUsers
463
+ .filter((user) => user !== file && !reachable.has(user))
464
+ .toSorted();
465
+ const elsewhere = everyUser.filter((user) => user !== file);
466
+ const usedInOwnFile = everyUser.includes(file);
467
+ const isUnusedOrUsedOnlyByTests =
468
+ elsewhere.every((user) => isUnderTestDirectory(user)) &&
469
+ !(usedInOwnFile && elsewhere.length > 0) &&
470
+ (elsewhere.length === 0 || !isWithin(file, SCRIPTS_DIRECTORY));
471
+ if (isUnusedOrUsedOnlyByTests) {
472
+ exportViolations.push(
473
+ elsewhere.length === 0
474
+ ? new UnusedExport({
475
+ location,
476
+ exportName: name,
477
+ ...(unreachableUser === undefined ? {} : { unreachableUser }),
478
+ })
479
+ : new TestOnlyExport({ location, exportName: name }),
480
+ );
481
+ }
482
+ }
483
+ }
484
+ const violations = [
485
+ ...entrySources
486
+ .filter(({ sources }) => sources.length === 0)
487
+ .map(({ entry }) => new PackageEntryWithoutSource({ entry })),
488
+ ...ownedPaths
489
+ .filter((file) => isTestEntryFile(file) && !runByScripts.has(file))
490
+ .map((file) => new TestNotRun({ location: file })),
491
+ ...exportViolations,
492
+ ...findMisplacedFiles({
493
+ paths,
494
+ importersOf: graph.importersOf,
495
+ moduleDirectories,
496
+ fixedFiles: new Set([
497
+ ...roots,
498
+ ...paths.filter(
499
+ (file) => !owned.has(file) || isDeclarationFile(file) || isUnderTestDirectory(file),
500
+ ),
501
+ ]),
502
+ }),
503
+ ];
504
+ if (violations.length > 0) {
505
+ return yield* new ExportPlacementViolations({ violations });
506
+ }
507
+ }).pipe(Effect.scoped);
@@ -0,0 +1,116 @@
1
+ import {
2
+ fileNameOf,
3
+ isEntryFileName,
4
+ isWithin,
5
+ LAYOUT_DIRECTORY_NAMES,
6
+ SHARED_DIRECTORY_NAME,
7
+ } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
8
+ import {
9
+ directoryOf,
10
+ enclosingDirectoriesOf,
11
+ isStrictlyUnder,
12
+ placementScopeOf,
13
+ } from "../../../shared/classify-files-by-role.ts";
14
+ import {
15
+ FileBesideSubdirectories,
16
+ FileOutsideModuleLayout,
17
+ SharedFileWithOneUser,
18
+ } from "./export-placement-errors.ts";
19
+ import { isSubdividedAmong } from "./find-subdivided-directories.ts";
20
+
21
+ export const findMisplacedFiles = ({
22
+ paths,
23
+ importersOf,
24
+ moduleDirectories,
25
+ fixedFiles,
26
+ }: {
27
+ readonly paths: readonly string[];
28
+ readonly importersOf: (file: string) => readonly string[];
29
+ readonly moduleDirectories: ReadonlySet<string>;
30
+ readonly fixedFiles: ReadonlySet<string>;
31
+ }) => {
32
+ const isSubdivided = isSubdividedAmong(paths);
33
+ const moduleEnclosing = (directory: string) =>
34
+ enclosingDirectoriesOf(`${directory}/`).findLast((enclosing) =>
35
+ moduleDirectories.has(enclosing),
36
+ );
37
+ const sharedFilesUsing = (file: string) => {
38
+ const sharedDirectory = directoryOf(file);
39
+ const found = new Set<string>();
40
+ const pending = [file];
41
+ for (const next of pending) {
42
+ for (const user of importersOf(next)) {
43
+ const isNewSharedUser =
44
+ directoryOf(user) === sharedDirectory && user !== file && !found.has(user);
45
+ if (isNewSharedUser) {
46
+ found.add(user);
47
+ pending.push(user);
48
+ }
49
+ }
50
+ }
51
+ return [...found].toSorted();
52
+ };
53
+ const submoduleUsing = (module: string, user: string) =>
54
+ enclosingDirectoriesOf(user).find(
55
+ (directory) => isStrictlyUnder(directory, module) && moduleDirectories.has(directory),
56
+ );
57
+ const sharedFileViolationOf = (file: string, module: string) => {
58
+ const sharedDirectory = directoryOf(file);
59
+ const through = sharedFilesUsing(file);
60
+ const users = [file, ...through]
61
+ .flatMap((user) => importersOf(user))
62
+ .filter((user) => user !== file && directoryOf(user) !== sharedDirectory);
63
+ const isUsedOnlyInsideTheModule =
64
+ users.length > 0 && users.every((user) => isWithin(user, module));
65
+ if (!isUsedOnlyInsideTheModule) {
66
+ return [];
67
+ }
68
+ const [part, ...otherParts] = new Set(users.map((user) => submoduleUsing(module, user)));
69
+ if (otherParts.length > 0) {
70
+ return [];
71
+ }
72
+ return [
73
+ new SharedFileWithOneUser({
74
+ location: file,
75
+ module,
76
+ ...(part === undefined ? {} : { part }),
77
+ ...(through.length === 0 ? {} : { through }),
78
+ }),
79
+ ];
80
+ };
81
+ const violationsOutsideModulesOf = (file: string) => {
82
+ const directory = directoryOf(file);
83
+ const isBesideSubdirectories =
84
+ directory === placementScopeOf(directory) && isSubdivided(directory);
85
+ return isBesideSubdirectories ? [new FileBesideSubdirectories({ location: file })] : [];
86
+ };
87
+ return paths
88
+ .filter((file) => !fixedFiles.has(file) && !isEntryFileName(fileNameOf(file)))
89
+ .flatMap(
90
+ (
91
+ file,
92
+ ): readonly (
93
+ | FileBesideSubdirectories
94
+ | FileOutsideModuleLayout
95
+ | SharedFileWithOneUser
96
+ )[] => {
97
+ if (importersOf(file).length === 0) {
98
+ return [];
99
+ }
100
+ const directory = directoryOf(file);
101
+ const module = moduleEnclosing(directory);
102
+ if (module === undefined) {
103
+ return violationsOutsideModulesOf(file);
104
+ }
105
+ if (directory === `${module}/${SHARED_DIRECTORY_NAME}`) {
106
+ return sharedFileViolationOf(file, module);
107
+ }
108
+ const isInALayoutDirectory = [...LAYOUT_DIRECTORY_NAMES].some((name) =>
109
+ isWithin(directory, `${module}/${name}`),
110
+ );
111
+ return isInALayoutDirectory
112
+ ? []
113
+ : [new FileOutsideModuleLayout({ location: file, module })];
114
+ },
115
+ );
116
+ };
@@ -0,0 +1,29 @@
1
+ import { TEST_DIRECTORY } from "../../../../../shared/test-home-directories.ts";
2
+ import {
3
+ directoryOf,
4
+ enclosingDirectoriesOf,
5
+ isScript,
6
+ isSpecialContainer,
7
+ } from "../../../shared/classify-files-by-role.ts";
8
+
9
+ const isTestDirectoryPath = (directory: string) =>
10
+ directory.split("/").some((segment) => segment === TEST_DIRECTORY);
11
+
12
+ const isSourceDirectory = (directory: string) =>
13
+ !isSpecialContainer(directory) && !isTestDirectoryPath(directory);
14
+
15
+ const subdividedDirectoriesAmong = (paths: readonly string[]) => {
16
+ const directoriesHoldingSources = new Set(
17
+ paths.filter((path) => isScript(path)).flatMap((path) => enclosingDirectoriesOf(path)),
18
+ );
19
+ return new Set(
20
+ [...directoriesHoldingSources]
21
+ .map((child) => directoryOf(child))
22
+ .filter((directory) => isSourceDirectory(directory)),
23
+ );
24
+ };
25
+
26
+ export const isSubdividedAmong = (paths: readonly string[]) => {
27
+ const subdivided = subdividedDirectoriesAmong(paths);
28
+ return (directory: string) => subdivided.has(directory);
29
+ };