@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,827 @@
1
+ import { Task } from "@sshkeda/task";
2
+ import { Effect, FileSystem, Option, Path, Predicate, References, Result, Schema } from "effect";
3
+ import { parseSync, Visitor } from "oxc-parser";
4
+ import type { CallExpression, Expression, ParseResult, Statement } from "oxc-parser";
5
+
6
+ import {
7
+ TASK_PACKAGE,
8
+ TASK_NAMESPACE_EXPORT,
9
+ TASK_MAIN_MEMBER,
10
+ } from "../../../../../shared/bans-each-permission-lifts.ts";
11
+ import { retiredWordIn } from "../../../../../shared/find-retired-words.ts";
12
+ import {
13
+ isEntryFileName,
14
+ fileNameOf,
15
+ isWithin,
16
+ LAYOUT_DIRECTORY_NAMES,
17
+ LIBRARY_DIRECTORY_NAME,
18
+ } from "../../../../../shared/match-file-names-and-path-prefixes.ts";
19
+ import {
20
+ cannotImportPermission,
21
+ RedundantGrant,
22
+ } from "../../../../../shared/permission-grant-errors.ts";
23
+ import {
24
+ generatedPathsOf,
25
+ DIRECTORY,
26
+ FILE_TYPE,
27
+ isMarkdown,
28
+ normalizedPath,
29
+ PATCH,
30
+ } from "../../../../../shared/record-and-grant-permissions-by-path.ts";
31
+ import type { PERMISSION_NAMES } from "../../../../../shared/record-and-grant-permissions-by-path.ts";
32
+ import {
33
+ SCRIPTS_DIRECTORY,
34
+ SOURCE_DIRECTORY,
35
+ TEST_DIRECTORY,
36
+ } from "../../../../../shared/test-home-directories.ts";
37
+ import {
38
+ enclosingDirectoriesOf,
39
+ isRootSupportFile,
40
+ repeatsSourceNeverImportsScripts,
41
+ moduleDirectoriesAmong,
42
+ isTopLevelScript,
43
+ isScript,
44
+ isDeclarationFile,
45
+ isUnderTestDirectory,
46
+ isPackageManifest,
47
+ directoryOf,
48
+ directoriesNestedInLayoutDirectoriesOf,
49
+ } from "../../../shared/classify-files-by-role.ts";
50
+ import { lineNumberAt } from "../../../shared/count-the-line-of-an-offset.ts";
51
+ import { PACKAGE_MANIFEST_FILE } from "../../../shared/find-named-package-manifests.ts";
52
+ import { isInsideAnyDirectory, listedPackageFiles } from "../../../shared/list-package-files.ts";
53
+ import { loadedLintConfigIn } from "../../../shared/load-the-lint-config.ts";
54
+ import {
55
+ bunPatchFileNameOf,
56
+ isGrantedPatchFile,
57
+ listedPatchesOf,
58
+ patchedDependenciesOf,
59
+ rootManifestIn,
60
+ } from "../../../shared/match-granted-patch-files.ts";
61
+ import { CHECK_PACKAGE } from "../../../shared/project-config-and-tool-errors.ts";
62
+ import {
63
+ JSON_OBJECT,
64
+ packageManifestObject,
65
+ } from "../../../shared/read-package-manifest-object.ts";
66
+ import { absolutePathOf } from "../../../shared/resolve-absolute-paths.ts";
67
+ import { toolFileOf, toolFileIsPlaced } from "../../../shared/tool-file-locations.ts";
68
+ import {
69
+ BunTestFileName,
70
+ CannotImportTargetMissing,
71
+ CheckOrTaskPatched,
72
+ DOCS_DIRECTORY,
73
+ FileLayoutViolations,
74
+ DirectoryGrantedPermissions,
75
+ DirectoryGrantOnFile,
76
+ DependencyOutsideRepository,
77
+ DirectoryHoldsOnlyADirectory,
78
+ RepositoryRootNotFound,
79
+ DuplicateFileName,
80
+ GrantedPathMissing,
81
+ LibraryDirectory,
82
+ DirectoryInInternalOrShared,
83
+ IndexInInternalOrShared,
84
+ SourceOutsideInternalOrShared,
85
+ MisplacedAtPackageRoot,
86
+ RetiredWordInPath,
87
+ NotKebabCase,
88
+ PackageScriptsField,
89
+ PatchedDependenciesMalformed,
90
+ PatchNotGranted,
91
+ MisplacedToolFile,
92
+ TopLevelNonScript,
93
+ TopLevelScriptHoldsOtherStatement,
94
+ TopLevelScriptWithoutMain,
95
+ UngrantedDocument,
96
+ UngrantedDirectory,
97
+ UnlistedPatchGranted,
98
+ } from "./file-layout-errors.ts";
99
+ import { exportPathMismatches } from "./find-export-path-mismatches.ts";
100
+ import {
101
+ directoriesOutsideModuleLayoutAmong,
102
+ isLibraryDirectoryOfAModule,
103
+ isModuleDirectory,
104
+ moduleLayoutViolations,
105
+ modulesWithLayoutDirectoryNamesAmong,
106
+ moduleWithLayoutDirectoryNameViolations,
107
+ } from "./find-module-layout-violations.ts";
108
+ import { taskImportsIn, isTaskLayoutFile } from "./resolve-task-imports.ts";
109
+
110
+ const KEBAB_CASE_PART = /^[a-z0-9]+(?:-[a-z0-9]+)*$/u;
111
+ const BUN_TEST_FILE_EXTENSION = /\.(?:test|spec)(?<extension>\.[^.]+)$/u;
112
+ const DIRECTORY_AND_FILE = 2;
113
+
114
+ const GRANTS_OF_A_REFUSED_CONFIG_ARE_REPORTED_BY_THE_LINT_CONFIG_TASK = Effect.succeedNone;
115
+
116
+ const isKebabCaseSegment = (segment: string) =>
117
+ toolFileOf(segment) !== undefined ||
118
+ segment
119
+ .replace(/^\./u, "")
120
+ .split(".")
121
+ .every((part) => KEBAB_CASE_PART.test(part));
122
+
123
+ const isNamedLikeABunTest = (fileName: string) => {
124
+ const extension = BUN_TEST_FILE_EXTENSION.exec(fileName.toLowerCase())?.groups?.["extension"];
125
+ return extension !== undefined && isScript(extension);
126
+ };
127
+
128
+ export const pathViolations = (path: string, isNamedByBunPatch = false) => {
129
+ const violations: (BunTestFileName | MisplacedToolFile | NotKebabCase | TopLevelNonScript)[] = [];
130
+ const segments = path.split("/");
131
+ const fileName = fileNameOf(path);
132
+ const tool = toolFileOf(path);
133
+ const misnamed = segments.find(
134
+ (segment, index) =>
135
+ !isKebabCaseSegment(segment) && !(isNamedByBunPatch && index === segments.length - 1),
136
+ );
137
+ if (misnamed !== undefined) {
138
+ violations.push(new NotKebabCase({ location: path, segment: misnamed }));
139
+ }
140
+ const isMisplacedTool = tool?.directories !== undefined && !toolFileIsPlaced(path);
141
+ if (isMisplacedTool) {
142
+ violations.push(new MisplacedToolFile({ location: path, directories: tool.directories }));
143
+ }
144
+ if (isNamedLikeABunTest(fileName)) {
145
+ violations.push(new BunTestFileName({ location: path }));
146
+ }
147
+ const isPlacedNonDocumentTool = tool !== undefined && toolFileIsPlaced(path) && !isMarkdown(path);
148
+ const isNonScriptDirectlyInScriptsDirectory =
149
+ segments.length === DIRECTORY_AND_FILE &&
150
+ segments[0] === SCRIPTS_DIRECTORY &&
151
+ !isScript(fileName.toLowerCase()) &&
152
+ !isMisplacedTool &&
153
+ !isPlacedNonDocumentTool;
154
+ if (isNonScriptDirectlyInScriptsDirectory) {
155
+ violations.push(new TopLevelNonScript({ location: path }));
156
+ }
157
+ return violations;
158
+ };
159
+
160
+ const directTaskImports = (parsed: ParseResult) =>
161
+ new Map(
162
+ parsed.module.staticImports
163
+ .filter((declaration) => declaration.moduleRequest.value === TASK_PACKAGE)
164
+ .flatMap((declaration) =>
165
+ declaration.entries
166
+ .filter((entry) => !entry.isType)
167
+ .map(
168
+ (entry) =>
169
+ [
170
+ entry.localName.value,
171
+ entry.importName.kind === "NamespaceObject" ? [] : [entry.importName.name ?? ""],
172
+ ] as const,
173
+ ),
174
+ ),
175
+ );
176
+
177
+ const callsTaskMember = (
178
+ parsed: ParseResult,
179
+ member: string,
180
+ imports: ReadonlyMap<string, readonly string[]>,
181
+ ) => {
182
+ const calls: CallExpression[] = [];
183
+ const aliases = new Map<string, Expression>();
184
+ new Visitor({
185
+ CallExpression(node) {
186
+ calls.push(node);
187
+ },
188
+ VariableDeclarator({ id, init: initializer }) {
189
+ const isNamedInitializer = id.type === "Identifier" && initializer !== null;
190
+ if (isNamedInitializer) {
191
+ aliases.set(id.name, initializer);
192
+ }
193
+ },
194
+ }).visit(parsed.program);
195
+ const taskReference = (
196
+ expression: Expression,
197
+ seen: ReadonlySet<string> = new Set(),
198
+ ): readonly string[] | undefined => {
199
+ if (expression.type === "Identifier") {
200
+ const imported = imports.get(expression.name);
201
+ if (imported !== undefined) {
202
+ return imported;
203
+ }
204
+ const alias = aliases.get(expression.name);
205
+ const isUnfollowedAlias = alias !== undefined && !seen.has(expression.name);
206
+ return isUnfollowedAlias
207
+ ? taskReference(alias, new Set([...seen, expression.name]))
208
+ : undefined;
209
+ }
210
+ const isStaticMember =
211
+ expression.type === "MemberExpression" &&
212
+ !expression.computed &&
213
+ expression.property.type === "Identifier";
214
+ if (!isStaticMember) {
215
+ return;
216
+ }
217
+ const object = taskReference(expression.object, seen);
218
+ return object === undefined ? undefined : [...object, expression.property.name];
219
+ };
220
+ return calls.some(
221
+ ({ callee }) => taskReference(callee)?.join(".") === `${TASK_NAMESPACE_EXPORT}.${member}`,
222
+ );
223
+ };
224
+
225
+ const importedMemberPath = (
226
+ expression: Expression,
227
+ imports: ReadonlyMap<string, readonly string[]>,
228
+ ): readonly string[] | undefined => {
229
+ if (expression.type === "Identifier") {
230
+ return imports.get(expression.name);
231
+ }
232
+ const isStaticMember =
233
+ expression.type === "MemberExpression" &&
234
+ !expression.computed &&
235
+ expression.property.type === "Identifier";
236
+ if (!isStaticMember) {
237
+ return;
238
+ }
239
+ const object = importedMemberPath(expression.object, imports);
240
+ return object === undefined ? undefined : [...object, expression.property.name];
241
+ };
242
+
243
+ const isMainGuard = (statement: Statement, imports: ReadonlyMap<string, readonly string[]>) => {
244
+ if (statement.type !== "IfStatement") {
245
+ return false;
246
+ }
247
+ const { test, consequent, alternate } = statement;
248
+ const testsImportMetaMain =
249
+ test.type === "MemberExpression" &&
250
+ !test.computed &&
251
+ test.object.type === "MetaProperty" &&
252
+ test.object.meta.name === "import" &&
253
+ test.object.property.name === "meta" &&
254
+ test.property.type === "Identifier" &&
255
+ test.property.name === "main";
256
+ const [only, ...others] = consequent.type === "BlockStatement" ? consequent.body : [];
257
+ const expression = only?.type === "ExpressionStatement" ? only.expression : undefined;
258
+ const call = expression?.type === "CallExpression" ? expression : undefined;
259
+ const [task, ...otherArguments] = call?.arguments ?? [];
260
+ const runsOneNamedTask =
261
+ call !== undefined &&
262
+ others.length === 0 &&
263
+ otherArguments.length === 0 &&
264
+ task?.type === "Identifier" &&
265
+ importedMemberPath(call.callee, imports)?.join(".") ===
266
+ `${TASK_NAMESPACE_EXPORT}.${TASK_MAIN_MEMBER}`;
267
+ return testsImportMetaMain && alternate === null && runsOneNamedTask;
268
+ };
269
+
270
+ const statementsOtherThanImportsAndMain = (
271
+ parsed: ParseResult,
272
+ imports: ReadonlyMap<string, readonly string[]>,
273
+ ) => {
274
+ const nonImports = parsed.program.body.filter(
275
+ (statement) => statement.type !== "ImportDeclaration",
276
+ );
277
+ const firstGuard = nonImports.findIndex((statement) => isMainGuard(statement, imports));
278
+ return nonImports.filter((_statement, index) => index !== firstGuard);
279
+ };
280
+
281
+ export const sourceViolations = (
282
+ path: string,
283
+ text: string,
284
+ resolvedImports?: ReadonlyMap<string, readonly string[]>,
285
+ ) => {
286
+ const violations: (
287
+ | MisplacedAtPackageRoot
288
+ | SourceOutsideInternalOrShared
289
+ | TopLevelScriptHoldsOtherStatement
290
+ | TopLevelScriptWithoutMain
291
+ )[] = [];
292
+ const isMisplacedTool = toolFileOf(path) !== undefined && !toolFileIsPlaced(path);
293
+ if (isMisplacedTool) {
294
+ return violations;
295
+ }
296
+
297
+ const isSourceOutsideModuleImplementation =
298
+ (isWithin(path, SOURCE_DIRECTORY) || isWithin(path, TEST_DIRECTORY)) &&
299
+ !isLibraryDirectoryOfAModule(directoryOf(path)) &&
300
+ !isEntryFileName(fileNameOf(path)) &&
301
+ !isDeclarationFile(path) &&
302
+ !enclosingDirectoriesOf(path).some((directory) =>
303
+ LAYOUT_DIRECTORY_NAMES.has(fileNameOf(directory)),
304
+ );
305
+ if (isSourceOutsideModuleImplementation) {
306
+ violations.push(new SourceOutsideInternalOrShared({ location: path }));
307
+ }
308
+
309
+ const parsed = parseSync(path, text);
310
+ const imports = resolvedImports ?? directTaskImports(parsed);
311
+ const isRootCodeFile = !path.includes("/") && !isRootSupportFile(path);
312
+ if (isRootCodeFile) {
313
+ violations.push(
314
+ new MisplacedAtPackageRoot({
315
+ location: path,
316
+ place: callsTaskMember(parsed, TASK_MAIN_MEMBER, imports)
317
+ ? "root-task-script"
318
+ : "root-code-file",
319
+ }),
320
+ );
321
+ }
322
+ const isTopLevelScriptWithoutMain =
323
+ isTopLevelScript(path) && !callsTaskMember(parsed, TASK_MAIN_MEMBER, imports);
324
+ if (isTopLevelScriptWithoutMain) {
325
+ violations.push(new TopLevelScriptWithoutMain({ location: path }));
326
+ }
327
+ const isTopLevelScriptWithMain = isTopLevelScript(path) && !isTopLevelScriptWithoutMain;
328
+ if (isTopLevelScriptWithMain) {
329
+ violations.push(
330
+ ...statementsOtherThanImportsAndMain(parsed, imports).map(
331
+ (statement) =>
332
+ new TopLevelScriptHoldsOtherStatement({
333
+ location: `${path}:${lineNumberAt(text, statement.start)}`,
334
+ }),
335
+ ),
336
+ );
337
+ }
338
+ return violations;
339
+ };
340
+
341
+ const directoryNameWords = (directoryName: string) =>
342
+ directoryName.replace(/^\./u, "").split(/[-_.]/u);
343
+
344
+ const nameViolationsOf = (path: string, words: readonly string[]) => {
345
+ const retired = retiredWordIn(words);
346
+ return retired === undefined ? [] : [new RetiredWordInPath({ location: path, ...retired })];
347
+ };
348
+
349
+ const distinctDirectoriesOf = (paths: readonly string[]) => [
350
+ ...new Set(paths.flatMap((path) => enclosingDirectoriesOf(path))),
351
+ ];
352
+
353
+ const outermostDirectoriesOf = (directories: readonly string[]) =>
354
+ directories.filter((directory) => !isInsideAnyDirectory(directory, directories));
355
+
356
+ const shapeViolationsOf = (paths: readonly string[]) => {
357
+ const directories = distinctDirectoriesOf(paths);
358
+ const directoriesOutsideModuleLayout = directoriesOutsideModuleLayoutAmong(paths);
359
+ return [
360
+ ...moduleLayoutViolations(paths),
361
+ ...directories
362
+ .filter((directory) => {
363
+ const isLibraryDirectoryOutsideAModule =
364
+ directory.endsWith(`/${LIBRARY_DIRECTORY_NAME}`) &&
365
+ !isModuleDirectory(directoryOf(directory));
366
+ return (
367
+ isLibraryDirectoryOutsideAModule &&
368
+ !isInsideAnyDirectory(directory, directoriesOutsideModuleLayout)
369
+ );
370
+ })
371
+ .map((directory) => new LibraryDirectory({ location: directory })),
372
+ ...[
373
+ ...new Set(
374
+ paths
375
+ .filter((path) => isScript(path) && !isUnderTestDirectory(path))
376
+ .flatMap((path) => directoriesNestedInLayoutDirectoriesOf(path)),
377
+ ),
378
+ ].map(
379
+ (directory) =>
380
+ new DirectoryInInternalOrShared({ location: directoryOf(directory), directory }),
381
+ ),
382
+ ...paths
383
+ .filter(
384
+ (path) =>
385
+ isEntryFileName(fileNameOf(path)) &&
386
+ LAYOUT_DIRECTORY_NAMES.has(fileNameOf(directoryOf(path))),
387
+ )
388
+ .map((path) => new IndexInInternalOrShared({ location: path })),
389
+ ];
390
+ };
391
+
392
+ export const directoryShapeViolations = (paths: readonly string[]) => {
393
+ const modulesWithLayoutDirectoryNames = modulesWithLayoutDirectoryNamesAmong(paths);
394
+ return [
395
+ ...moduleWithLayoutDirectoryNameViolations(paths),
396
+ ...shapeViolationsOf(paths).filter(
397
+ ({ location }) =>
398
+ !modulesWithLayoutDirectoryNames.some((module) => isWithin(location, module)),
399
+ ),
400
+ ];
401
+ };
402
+
403
+ const PACKAGE_ROOT_SCOPE = "";
404
+ const PACKAGE_ROOT_DIRECTORIES: ReadonlySet<string> = new Set([
405
+ SOURCE_DIRECTORY,
406
+ SCRIPTS_DIRECTORY,
407
+ TEST_DIRECTORY,
408
+ DOCS_DIRECTORY,
409
+ ]);
410
+
411
+ export const directoriesHoldingOnlyADirectory = (
412
+ paths: readonly string[],
413
+ nestedPackageDirectories: readonly string[],
414
+ ) => {
415
+ const outermostPackageDirectories = outermostDirectoriesOf(nestedPackageDirectories);
416
+ const directories = new Set([
417
+ ...distinctDirectoriesOf([...paths, ...outermostPackageDirectories]),
418
+ ...outermostPackageDirectories,
419
+ ]);
420
+ const entriesByDirectory = Map.groupBy([...paths, ...directories], directoryOf);
421
+ return [...directories].flatMap((directory) => {
422
+ const [only, ...others] = entriesByDirectory.get(directory) ?? [];
423
+ const holdsOnlyADirectory =
424
+ only !== undefined &&
425
+ others.length === 0 &&
426
+ directories.has(only) &&
427
+ !isLibraryDirectoryOfAModule(directory);
428
+ return holdsOnlyADirectory
429
+ ? [new DirectoryHoldsOnlyADirectory({ location: directory, child: fileNameOf(only) })]
430
+ : [];
431
+ });
432
+ };
433
+
434
+ const SCRIPT_EXTENSION = /\.[cm]?[jt]sx?$/u;
435
+
436
+ const moduleNameOf = (path: string) => fileNameOf(path).replace(SCRIPT_EXTENSION, "");
437
+
438
+ export const duplicateFileNameViolations = (paths: readonly string[]) => {
439
+ const moduleDirectories = moduleDirectoriesAmong(paths);
440
+ const nameScopeOf = (path: string) =>
441
+ enclosingDirectoriesOf(path)
442
+ .toReversed()
443
+ .find(
444
+ (directory) =>
445
+ moduleDirectories.has(directory) ||
446
+ directory === TEST_DIRECTORY ||
447
+ directory === SCRIPTS_DIRECTORY,
448
+ ) ?? PACKAGE_ROOT_SCOPE;
449
+ const sources = paths.filter((path) => isScript(path) && !isEntryFileName(fileNameOf(path)));
450
+ const sourcesByScopedName = Map.groupBy(
451
+ sources,
452
+ (path) => `${nameScopeOf(path)}/${moduleNameOf(path)}`,
453
+ );
454
+ return [...sourcesByScopedName.values()].flatMap((sameNamed) =>
455
+ sameNamed.length === 1
456
+ ? []
457
+ : sameNamed.map(
458
+ (path) =>
459
+ new DuplicateFileName({
460
+ location: path,
461
+ otherPaths: sameNamed.filter((other) => other !== path),
462
+ scope: nameScopeOf(path),
463
+ }),
464
+ ),
465
+ );
466
+ };
467
+
468
+ export const packageRootViolations = (paths: readonly string[]) =>
469
+ paths
470
+ .filter((path) => {
471
+ const isMisplacedTool = toolFileOf(path) !== undefined && !toolFileIsPlaced(path);
472
+ return isWithin(path, DOCS_DIRECTORY) && !isMarkdown(path) && !isMisplacedTool;
473
+ })
474
+ .map((path) => new MisplacedAtPackageRoot({ location: path, place: "docs-non-markdown" }));
475
+
476
+ export const directoryNameViolations = (paths: readonly string[]) =>
477
+ distinctDirectoriesOf(paths).flatMap((directory) =>
478
+ nameViolationsOf(directory, directoryNameWords(fileNameOf(directory))),
479
+ );
480
+
481
+ const DEPENDENCY_FIELDS = [
482
+ "dependencies",
483
+ "devDependencies",
484
+ "peerDependencies",
485
+ "optionalDependencies",
486
+ "overrides",
487
+ ] as const;
488
+ const LOCAL_PATH_PROTOCOL = /^(?:file|link):/u;
489
+ const BARE_LOCAL_PATH = /^(?:\.{1,2}(?:\/|$)|\/)/u;
490
+ const isJsonObject = Schema.is(JSON_OBJECT);
491
+
492
+ const localPathOf = (specifier: string) => {
493
+ if (LOCAL_PATH_PROTOCOL.test(specifier)) {
494
+ return specifier.replace(LOCAL_PATH_PROTOCOL, "");
495
+ }
496
+ return BARE_LOCAL_PATH.test(specifier) ? specifier : undefined;
497
+ };
498
+
499
+ const specifiersIn = (
500
+ field: string,
501
+ value: Schema.Json | undefined,
502
+ ): { field: string; specifier: string }[] => {
503
+ if (typeof value === "string") {
504
+ return [{ field, specifier: value }];
505
+ }
506
+ if (!isJsonObject(value)) {
507
+ return [];
508
+ }
509
+ return Object.entries(value).flatMap(([name, nested]) =>
510
+ specifiersIn(`${field}.${name}`, nested),
511
+ );
512
+ };
513
+
514
+ const isOutsideDirectory = (pathModule: Path.Path, directory: string, target: string) => {
515
+ const fromDirectory = pathModule.relative(directory, target);
516
+ return (
517
+ fromDirectory === ".." ||
518
+ fromDirectory.startsWith("../") ||
519
+ pathModule.isAbsolute(fromDirectory)
520
+ );
521
+ };
522
+
523
+ export const dependenciesOutsideRepository = (
524
+ path: string,
525
+ manifest: typeof JSON_OBJECT.Type,
526
+ repository: { readonly root: string; readonly packageDirectory: string },
527
+ ) =>
528
+ Effect.gen(function* () {
529
+ const pathModule = yield* Path.Path;
530
+ const manifestDirectory = pathModule.join(
531
+ repository.packageDirectory,
532
+ pathModule.dirname(path),
533
+ );
534
+ return DEPENDENCY_FIELDS.flatMap((field) => specifiersIn(field, manifest[field])).flatMap(
535
+ ({ field, specifier }) => {
536
+ const localPath = localPathOf(specifier);
537
+ if (localPath === undefined) {
538
+ return [];
539
+ }
540
+ return isOutsideDirectory(
541
+ pathModule,
542
+ repository.root,
543
+ pathModule.resolve(manifestDirectory, localPath),
544
+ )
545
+ ? [new DependencyOutsideRepository({ location: path, field, specifier })]
546
+ : [];
547
+ },
548
+ );
549
+ });
550
+
551
+ export const manifestViolations = (
552
+ path: string,
553
+ text: string,
554
+ repository: Parameters<typeof dependenciesOutsideRepository>[2],
555
+ ) =>
556
+ Effect.gen(function* () {
557
+ const manifest = packageManifestObject(path, text);
558
+ if (Result.isFailure(manifest)) {
559
+ return [manifest.failure];
560
+ }
561
+ const scriptsViolations = Predicate.hasProperty(manifest.success, "scripts")
562
+ ? [new PackageScriptsField({ location: path })]
563
+ : [];
564
+ return [
565
+ ...scriptsViolations,
566
+ ...(yield* dependenciesOutsideRepository(path, manifest.success, repository)),
567
+ ...exportPathMismatches(path, manifest.success),
568
+ ];
569
+ });
570
+
571
+ const ROOT_README = "README.md";
572
+
573
+ export const permissionGrantViolations = (
574
+ paths: readonly string[],
575
+ grants: Effect.Success<ReturnType<typeof loadedLintConfigIn>>,
576
+ nestedPackageDirectories: readonly string[] = [],
577
+ ) => {
578
+ const repositoryFiles = new Set(paths);
579
+ const generated = generatedPathsOf(grants);
580
+ const outermostPackageDirectories = outermostDirectoriesOf(nestedPackageDirectories);
581
+ const repositoryDirectories = new Set([
582
+ ...distinctDirectoriesOf([...paths, ...outermostPackageDirectories]),
583
+ ...outermostPackageDirectories,
584
+ ]);
585
+ const ownedDirectories = new Set([
586
+ ...distinctDirectoriesOf([
587
+ ...paths.filter((file) => !generated.has(file)),
588
+ ...outermostPackageDirectories,
589
+ ]),
590
+ ...outermostPackageDirectories,
591
+ ]);
592
+ const directoriesNeedingGrants = [...ownedDirectories].filter(
593
+ (directory) => !directory.includes("/") && !PACKAGE_ROOT_DIRECTORIES.has(directory),
594
+ );
595
+ const violations: (
596
+ | CannotImportTargetMissing
597
+ | DirectoryGrantedPermissions
598
+ | DirectoryGrantOnFile
599
+ | GrantedPathMissing
600
+ | RedundantGrant
601
+ | UngrantedDirectory
602
+ | UngrantedDocument
603
+ )[] = [];
604
+ const isGranted = (path: string, permission: (typeof PERMISSION_NAMES)[number]) =>
605
+ grants.some((grant) => grant.path === path && grant.allow.includes(permission));
606
+ for (const path of paths) {
607
+ const isUngrantedDocument =
608
+ isMarkdown(path) &&
609
+ path !== ROOT_README &&
610
+ !generated.has(path) &&
611
+ !isGranted(path, FILE_TYPE);
612
+ if (isUngrantedDocument) {
613
+ violations.push(new UngrantedDocument({ location: path }));
614
+ }
615
+ }
616
+ const holdsOnlyGrantedPatches = (directory: string) => {
617
+ const held = paths.filter((path) => isWithin(path, directory));
618
+ return held.length > 0 && held.every((path) => isGrantedPatchFile(path, grants));
619
+ };
620
+ for (const directory of directoriesNeedingGrants) {
621
+ const isGrantedDirectory =
622
+ isGranted(directory, DIRECTORY) ||
623
+ isGranted(directory, PATCH) ||
624
+ holdsOnlyGrantedPatches(directory);
625
+ if (!isGrantedDirectory) {
626
+ violations.push(new UngrantedDirectory({ location: directory }));
627
+ }
628
+ }
629
+ const isRepositoryDirectory = (path: string) => repositoryDirectories.has(path);
630
+ const exists = (path: string) => repositoryFiles.has(path) || isRepositoryDirectory(path);
631
+ for (const grant of grants) {
632
+ if (!exists(grant.path)) {
633
+ violations.push(new GrantedPathMissing({ path: grant.path }));
634
+ }
635
+ const grantsDirectoryToFile =
636
+ repositoryFiles.has(grant.path) && grant.allow.includes(DIRECTORY);
637
+ if (grantsDirectoryToFile) {
638
+ violations.push(new DirectoryGrantOnFile({ path: grant.path }));
639
+ }
640
+ const isDirectoryGrantedPermissions =
641
+ isRepositoryDirectory(grant.path) &&
642
+ (grant.allow.some((permission) => permission !== DIRECTORY && permission !== PATCH) ||
643
+ grant.services.length > 0);
644
+ if (isDirectoryGrantedPermissions) {
645
+ violations.push(new DirectoryGrantedPermissions({ path: grant.path }));
646
+ }
647
+ const grantsFileTypeToRootReadme =
648
+ grant.path === ROOT_README && grant.allow.includes(FILE_TYPE);
649
+ if (grantsFileTypeToRootReadme) {
650
+ violations.push(
651
+ new RedundantGrant({
652
+ path: grant.path,
653
+ permission: FILE_TYPE,
654
+ reason: "the root README.md needs no grant",
655
+ }),
656
+ );
657
+ }
658
+ for (const target of grant.cannotImport.filter((candidate) => !exists(candidate))) {
659
+ violations.push(new CannotImportTargetMissing({ path: grant.path, target }));
660
+ }
661
+ for (const target of grant.cannotImport.filter((candidate) =>
662
+ repeatsSourceNeverImportsScripts(grant.path, candidate),
663
+ )) {
664
+ violations.push(
665
+ new RedundantGrant({
666
+ path: grant.path,
667
+ permission: cannotImportPermission(target),
668
+ reason: `files in ${SOURCE_DIRECTORY}/ cannot import ${SCRIPTS_DIRECTORY}/`,
669
+ }),
670
+ );
671
+ }
672
+ }
673
+ return violations;
674
+ };
675
+
676
+ export const patchGrantViolations = (
677
+ manifest: typeof JSON_OBJECT.Type,
678
+ grants: Effect.Success<ReturnType<typeof loadedLintConfigIn>>,
679
+ ) => {
680
+ const patchedDependencies = patchedDependenciesOf(manifest);
681
+ if (Result.isFailure(patchedDependencies)) {
682
+ return [
683
+ new PatchedDependenciesMalformed({
684
+ location: PACKAGE_MANIFEST_FILE,
685
+ reason: patchedDependencies.failure.message,
686
+ }),
687
+ ];
688
+ }
689
+ const patches = Object.entries(patchedDependencies.success).map(([dependency, patchPath]) => ({
690
+ dependency,
691
+ patchPath: normalizedPath(patchPath),
692
+ }));
693
+ const patchPaths = new Set(patches.map(({ patchPath }) => patchPath));
694
+ const patchGrants = grants.filter((grant) => grant.allow.includes(PATCH));
695
+ const grantedPatchPaths = new Set(patchGrants.map((grant) => grant.path));
696
+ return [
697
+ ...patches.flatMap(({ dependency, patchPath }) => {
698
+ const patchesCheckOrTask = [CHECK_PACKAGE, TASK_PACKAGE].some((name) => {
699
+ const namesPackage = dependency === name;
700
+ const namesVersion = dependency.startsWith(`${name}@`);
701
+ return namesPackage || namesVersion;
702
+ });
703
+ const isGrantedPatch =
704
+ grantedPatchPaths.has(patchPath) || grantedPatchPaths.has(directoryOf(patchPath));
705
+ const patchIsAllowed = !patchesCheckOrTask && isGrantedPatch;
706
+ if (patchIsAllowed) {
707
+ return [];
708
+ }
709
+ const fields = { location: PACKAGE_MANIFEST_FILE, dependency, patchPath };
710
+ return [patchesCheckOrTask ? new CheckOrTaskPatched(fields) : new PatchNotGranted(fields)];
711
+ }),
712
+ ...patchGrants
713
+ .filter(
714
+ (grant) =>
715
+ !patchPaths.has(grant.path) &&
716
+ ![...patchPaths].some((patchPath) => directoryOf(patchPath) === grant.path),
717
+ )
718
+ .map((grant) => new UnlistedPatchGranted({ path: grant.path })),
719
+ ];
720
+ };
721
+
722
+ const repositoryOf = (directory: string) =>
723
+ Effect.gen(function* () {
724
+ const repositoryRoot = yield* Task.exec("git", ["rev-parse", "--show-toplevel"], {
725
+ cwd: directory,
726
+ }).pipe(
727
+ Effect.provideService(References.MinimumLogLevel, "Warn"),
728
+ Effect.catchTag("CommandFailed", (failure) =>
729
+ Effect.fail(new RepositoryRootNotFound({ directory, reason: failure.message })),
730
+ ),
731
+ );
732
+ const packageDirectory = yield* FileSystem.FileSystem.use((fileSystem) =>
733
+ fileSystem.realPath(directory),
734
+ );
735
+ return { root: repositoryRoot.trim(), packageDirectory };
736
+ });
737
+
738
+ export const findFileLayoutViolations = (directory: string) =>
739
+ Effect.gen(function* () {
740
+ const fileSystem = yield* FileSystem.FileSystem;
741
+ const pathModule = yield* Path.Path;
742
+ const repository = yield* repositoryOf(directory);
743
+ const { packageFiles: paths, nestedPackageDirectories } = yield* listedPackageFiles(
744
+ directory,
745
+ [],
746
+ );
747
+ const grants = yield* loadedLintConfigIn(directory).pipe(
748
+ Effect.asSome,
749
+ Effect.catchTag(
750
+ "LintConfigRefused",
751
+ () => GRANTS_OF_A_REFUSED_CONFIG_ARE_REPORTED_BY_THE_LINT_CONFIG_TASK,
752
+ ),
753
+ );
754
+ const rootManifest = yield* rootManifestIn(directory, paths);
755
+ const generated = Option.match(grants, {
756
+ onNone: () => new Set<string>(),
757
+ onSome: generatedPathsOf,
758
+ });
759
+ const ownedPaths = paths.filter((file) => !generated.has(file));
760
+ const listedPatches = listedPatchesOf(rootManifest);
761
+ const isNamedByBunPatch = (path: string) =>
762
+ listedPatches.some(
763
+ ({ dependency, patchPath }) =>
764
+ patchPath === path && fileNameOf(path) === bunPatchFileNameOf(dependency),
765
+ ) &&
766
+ Option.match(grants, {
767
+ onNone: () => false,
768
+ onSome: (found) => isGrantedPatchFile(path, found),
769
+ });
770
+ const ownedDirectories = new Set(
771
+ distinctDirectoriesOf([...ownedPaths, ...nestedPackageDirectories]),
772
+ );
773
+ const grantViolations = Option.match(grants, {
774
+ onNone: () => [],
775
+ onSome: (found) => [
776
+ ...permissionGrantViolations(
777
+ [...new Set([...paths, ...generated])],
778
+ found,
779
+ nestedPackageDirectories,
780
+ ),
781
+ ...patchGrantViolations(rootManifest, found),
782
+ ],
783
+ });
784
+ const fileViolations = yield* Effect.forEach(
785
+ paths.filter((file) => !generated.has(file) || isPackageManifest(file)),
786
+ (path) =>
787
+ Effect.gen(function* () {
788
+ const found = pathViolations(path, isNamedByBunPatch(path));
789
+ const isScriptFile = isScript(path);
790
+ const isNeitherScriptNorManifest = !isScriptFile && !isPackageManifest(path);
791
+ if (isNeitherScriptNorManifest) {
792
+ return found;
793
+ }
794
+ const text = yield* fileSystem.readFileString(pathModule.join(directory, path));
795
+ const absoluteDirectory = yield* absolutePathOf(directory);
796
+ const imports = isTaskLayoutFile(path)
797
+ ? yield* taskImportsIn(
798
+ pathModule.join(absoluteDirectory, path),
799
+ text,
800
+ absoluteDirectory,
801
+ )
802
+ : undefined;
803
+ return [
804
+ ...found,
805
+ ...(isScriptFile
806
+ ? sourceViolations(path, text, imports)
807
+ : yield* manifestViolations(path, text, repository)),
808
+ ];
809
+ }),
810
+ { concurrency: "unbounded" },
811
+ );
812
+ const violations = [
813
+ ...fileViolations.flat(),
814
+ ...directoryNameViolations(ownedPaths),
815
+ ...directoryShapeViolations(ownedPaths),
816
+ ...directoriesHoldingOnlyADirectory(
817
+ [...new Set([...paths, ...generated])],
818
+ nestedPackageDirectories,
819
+ ).filter(({ location }) => ownedDirectories.has(location)),
820
+ ...packageRootViolations(ownedPaths),
821
+ ...duplicateFileNameViolations(ownedPaths),
822
+ ...grantViolations,
823
+ ];
824
+ if (violations.length > 0) {
825
+ return yield* new FileLayoutViolations({ violations });
826
+ }
827
+ });