@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,176 @@
1
+ import { Schema } from "effect";
2
+
3
+ import { listedViolations } from "../../../../../shared/format-reported-failures.ts";
4
+ import { SCRIPTS_DIRECTORY, TEST_DIRECTORY } from "../../../../../shared/test-home-directories.ts";
5
+ import { MODULE_URL_USAGES } from "../../../shared/find-module-requests.ts";
6
+
7
+ export class ImportResolvesToNoFile extends Schema.TaggedError<ImportResolvesToNoFile>()(
8
+ "ImportResolvesToNoFile",
9
+ { location: Schema.String, specifier: Schema.String },
10
+ ) {
11
+ public override get message() {
12
+ return `imports ${this.specifier}, which resolves to no file`;
13
+ }
14
+ }
15
+
16
+ export class ImportOfMissingIgnoredFile extends Schema.TaggedError<ImportOfMissingIgnoredFile>()(
17
+ "ImportOfMissingIgnoredFile",
18
+ { location: Schema.String, specifier: Schema.String, missingPath: Schema.String },
19
+ ) {
20
+ public override get message() {
21
+ return `imports ${this.specifier}, but ${this.missingPath} does not exist and is gitignored`;
22
+ }
23
+ }
24
+
25
+ export class ImportCaseMismatch extends Schema.TaggedError<ImportCaseMismatch>()(
26
+ "ImportCaseMismatch",
27
+ { location: Schema.String, specifier: Schema.String, importedFile: Schema.String },
28
+ ) {
29
+ public override get message() {
30
+ return `imports ${this.specifier}, which differs only in letter case from ${this.importedFile}`;
31
+ }
32
+ }
33
+
34
+ export class CannotImportCrossed extends Schema.TaggedError<CannotImportCrossed>()(
35
+ "CannotImportCrossed",
36
+ {
37
+ location: Schema.String,
38
+ importedPath: Schema.String,
39
+ grantPath: Schema.String,
40
+ target: Schema.String,
41
+ },
42
+ ) {
43
+ public override get message() {
44
+ return `imports ${this.importedPath}, and ${this.grantPath} cannot import ${this.target}`;
45
+ }
46
+ }
47
+
48
+ export class TestImported extends Schema.TaggedError<TestImported>()("TestImported", {
49
+ location: Schema.String,
50
+ importedPath: Schema.String,
51
+ }) {
52
+ public override get message() {
53
+ return `imports ${this.importedPath}, but only ${SCRIPTS_DIRECTORY}/ and ${TEST_DIRECTORY}/ may import ${TEST_DIRECTORY}/`;
54
+ }
55
+ }
56
+
57
+ export class DevDependencyImported extends Schema.TaggedError<DevDependencyImported>()(
58
+ "DevDependencyImported",
59
+ { location: Schema.String, specifier: Schema.String, packageName: Schema.String },
60
+ ) {
61
+ public override get message() {
62
+ return `imports ${this.specifier}, but package.json lists ${this.packageName} only in devDependencies, and src cannot import a dev dependency`;
63
+ }
64
+ }
65
+
66
+ export class ModuleInternalsImported extends Schema.TaggedError<ModuleInternalsImported>()(
67
+ "ModuleInternalsImported",
68
+ {
69
+ location: Schema.String,
70
+ importedPath: Schema.String,
71
+ module: Schema.String,
72
+ kind: Schema.Literals(["module", "package"]),
73
+ },
74
+ ) {
75
+ public override get message() {
76
+ return `imports ${this.importedPath}, inside ${this.kind} ${this.module}/, from outside it`;
77
+ }
78
+ }
79
+
80
+ export class PlainDirectoryImported extends Schema.TaggedError<PlainDirectoryImported>()(
81
+ "PlainDirectoryImported",
82
+ {
83
+ location: Schema.String,
84
+ importedPath: Schema.String,
85
+ directory: Schema.String,
86
+ parent: Schema.String,
87
+ },
88
+ ) {
89
+ public override get message() {
90
+ return `imports ${this.importedPath}, inside ${this.directory}/, which only ${this.parent}/ may import`;
91
+ }
92
+ }
93
+
94
+ export class PrivateCodeImported extends Schema.TaggedError<PrivateCodeImported>()(
95
+ "PrivateCodeImported",
96
+ {
97
+ location: Schema.String,
98
+ importedPath: Schema.String,
99
+ directory: Schema.String,
100
+ module: Schema.String,
101
+ },
102
+ ) {
103
+ public override get message() {
104
+ return `imports ${this.importedPath}, which is private to ${this.module}/: only its index and files in ${this.directory}/ may import it`;
105
+ }
106
+ }
107
+
108
+ export class ImportOutsidePackage extends Schema.TaggedError<ImportOutsidePackage>()(
109
+ "ImportOutsidePackage",
110
+ { location: Schema.String, specifier: Schema.String, importedFile: Schema.String },
111
+ ) {
112
+ public override get message() {
113
+ return `imports ${this.specifier}, which resolves to ${this.importedFile} outside the package`;
114
+ }
115
+ }
116
+
117
+ const MODULE_URL_USAGE_FACTS = {
118
+ stored: "stores import.meta.url in a variable",
119
+ computed: "builds a module URL from a computed path",
120
+ base: "builds a module URL on a base other than import.meta.url itself",
121
+ other: 'uses import.meta.url outside new URL("…", import.meta.url)',
122
+ } as const satisfies Readonly<Record<(typeof MODULE_URL_USAGES)[number], string>>;
123
+
124
+ export class ModuleUrlNotInline extends Schema.TaggedError<ModuleUrlNotInline>()(
125
+ "ModuleUrlNotInline",
126
+ { location: Schema.String, usage: Schema.Literals(MODULE_URL_USAGES) },
127
+ ) {
128
+ public override get message() {
129
+ return MODULE_URL_USAGE_FACTS[this.usage];
130
+ }
131
+ }
132
+
133
+ export class ModuleUrlPassedToFunction extends Schema.TaggedError<ModuleUrlPassedToFunction>()(
134
+ "ModuleUrlPassedToFunction",
135
+ { location: Schema.String, callee: Schema.String },
136
+ ) {
137
+ public override get message() {
138
+ return `passes import.meta.url to ${this.callee}`;
139
+ }
140
+ }
141
+
142
+ export class ModulePathFromDirectory extends Schema.TaggedError<ModulePathFromDirectory>()(
143
+ "ModulePathFromDirectory",
144
+ { location: Schema.String, property: Schema.String },
145
+ ) {
146
+ public override get message() {
147
+ return `builds a module path from import.meta.${this.property}`;
148
+ }
149
+ }
150
+
151
+ export const IMPORT_BOUNDARY_VIOLATION = Schema.Union([
152
+ ModuleUrlNotInline,
153
+ ModuleUrlPassedToFunction,
154
+ ModulePathFromDirectory,
155
+ ImportResolvesToNoFile,
156
+ ImportOfMissingIgnoredFile,
157
+ ImportCaseMismatch,
158
+ ImportOutsidePackage,
159
+ CannotImportCrossed,
160
+ TestImported,
161
+ DevDependencyImported,
162
+ ModuleInternalsImported,
163
+ PlainDirectoryImported,
164
+ PrivateCodeImported,
165
+ ]);
166
+
167
+ export class ImportBoundariesCrossed extends Schema.TaggedError<ImportBoundariesCrossed>()(
168
+ "ImportBoundariesCrossed",
169
+ {
170
+ violations: Schema.Array(IMPORT_BOUNDARY_VIOLATION),
171
+ },
172
+ ) {
173
+ public override get message() {
174
+ return listedViolations(this.violations);
175
+ }
176
+ }
@@ -0,0 +1 @@
1
+ export { findDeclaredUseViolations } from "./internal/find-declared-use-violations.ts";
@@ -0,0 +1,32 @@
1
+ import { Schema } from "effect";
2
+
3
+ import { listedViolations } from "../../../../../shared/format-reported-failures.ts";
4
+
5
+ export class SyncCall extends Schema.TaggedError<SyncCall>()("SyncCall", {
6
+ location: Schema.String,
7
+ api: Schema.String,
8
+ }) {
9
+ public override get message() {
10
+ return `${this.api} runs synchronously`;
11
+ }
12
+ }
13
+
14
+ export class SchemaUsedOnlyAsType extends Schema.TaggedError<SchemaUsedOnlyAsType>()(
15
+ "SchemaUsedOnlyAsType",
16
+ { location: Schema.String, schemaName: Schema.String },
17
+ ) {
18
+ public override get message() {
19
+ return `${this.schemaName} is a schema used only as a type`;
20
+ }
21
+ }
22
+
23
+ export class DeclaredUsesRefused extends Schema.TaggedError<DeclaredUsesRefused>()(
24
+ "DeclaredUsesRefused",
25
+ {
26
+ violations: Schema.Array(Schema.Union([SyncCall, SchemaUsedOnlyAsType])),
27
+ },
28
+ ) {
29
+ public override get message() {
30
+ return listedViolations(this.violations);
31
+ }
32
+ }
@@ -0,0 +1,38 @@
1
+ import { Effect, Path } from "effect";
2
+
3
+ import { packageCalleesIn } from "../../../shared/query-the-typescript-project.ts";
4
+ import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
5
+ import { absolutePathOf } from "../../../shared/resolve-absolute-paths.ts";
6
+ import { DeclaredUsesRefused } from "./declared-use-errors.ts";
7
+ import { findSyncCalls } from "./find-sync-calls.ts";
8
+ import { findTypeOnlySchemas } from "./find-type-only-schemas.ts";
9
+
10
+ export const findDeclaredUseViolations = <OpeningError, OpeningRequirement>(
11
+ projectFile: string,
12
+ openedProjects: Effect.Effect<
13
+ Effect.Success<ReturnType<typeof openTypeScriptProjects>>,
14
+ OpeningError,
15
+ OpeningRequirement
16
+ >,
17
+ ) =>
18
+ Effect.gen(function* () {
19
+ const path = yield* Path.Path;
20
+ const projectDirectory = path.dirname(yield* absolutePathOf(projectFile));
21
+ const violations: DeclaredUsesRefused["violations"][number][] = [];
22
+ const projects = yield* openedProjects;
23
+ for (const project of projects) {
24
+ for (const { sourceFile, displayName } of project.sourceFiles) {
25
+ violations.push(
26
+ ...findSyncCalls(
27
+ sourceFile,
28
+ displayName,
29
+ yield* packageCalleesIn(project.checker, projectDirectory, sourceFile),
30
+ ),
31
+ );
32
+ }
33
+ }
34
+ violations.push(...(yield* findTypeOnlySchemas(projects)));
35
+ if (violations.length > 0) {
36
+ return yield* new DeclaredUsesRefused({ violations });
37
+ }
38
+ }).pipe(Effect.scoped);
@@ -0,0 +1,23 @@
1
+ import type { Effect } from "effect";
2
+ import type { SourceFile } from "typescript/unstable/ast";
3
+
4
+ import { isDeclaredSync } from "../../../../../shared/bans-each-permission-lifts.ts";
5
+ import { nodePosition } from "../../../shared/query-the-typescript-project.ts";
6
+ import type { packageCalleesIn } from "../../../shared/query-the-typescript-project.ts";
7
+ import { SyncCall } from "./declared-use-errors.ts";
8
+
9
+ export const findSyncCalls = (
10
+ sourceFile: SourceFile,
11
+ displayName: string,
12
+ callees: Effect.Success<ReturnType<typeof packageCalleesIn>>,
13
+ ) =>
14
+ callees.flatMap(({ call, name, className }) =>
15
+ isDeclaredSync(name)
16
+ ? [
17
+ new SyncCall({
18
+ location: `${displayName}:${nodePosition(sourceFile, call).line}`,
19
+ api: className === undefined ? name : `${className}.${name}`,
20
+ }),
21
+ ]
22
+ : [],
23
+ );
@@ -0,0 +1,375 @@
1
+ import { Effect } from "effect";
2
+ import type { Schema } from "effect";
3
+ import { NodeFlags, SyntaxKind } from "typescript/unstable/ast";
4
+ import type { Identifier, Node, SourceFile } from "typescript/unstable/ast";
5
+ import {
6
+ isCallExpression,
7
+ isClassDeclaration,
8
+ isExportDeclaration,
9
+ isExportSpecifier,
10
+ isIdentifier,
11
+ isImportClause,
12
+ isImportDeclaration,
13
+ isImportEqualsDeclaration,
14
+ isImportSpecifier,
15
+ isImportTypeNode,
16
+ isNamespaceExport,
17
+ isNamespaceImport,
18
+ isPropertyAccessExpression,
19
+ isQualifiedName,
20
+ isStringLiteralLikeNode,
21
+ isTypeQueryNode,
22
+ isTypeReferenceNode,
23
+ isVariableDeclaration,
24
+ } from "typescript/unstable/ast/is";
25
+ import type { Checker, NodeHandle } from "typescript/unstable/async";
26
+
27
+ import {
28
+ CONCURRENT_TYPESCRIPT_REQUESTS,
29
+ followedImportAliases,
30
+ nodePosition,
31
+ parentOf,
32
+ resolvedSymbols,
33
+ typeScriptRequest,
34
+ valueSymbolAt,
35
+ } from "../../../shared/query-the-typescript-project.ts";
36
+ import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
37
+ import { SchemaUsedOnlyAsType } from "./declared-use-errors.ts";
38
+
39
+ const SCHEMA_TYPE_ID = "~effect/Schema/Schema" satisfies keyof Schema.Top;
40
+ const DEFAULT_EXPORT_NAME = "default";
41
+
42
+ const nodesIn = <Found extends Node>(root: Node, isWanted: (node: Node) => node is Found) => {
43
+ const found: Found[] = [];
44
+ const visit = (node: Node) => {
45
+ if (isWanted(node)) {
46
+ found.push(node);
47
+ }
48
+ node.forEachChild(visit);
49
+ };
50
+ root.forEachChild(visit);
51
+ return found;
52
+ };
53
+
54
+ const ancestorsOf = (node: Node): readonly Node[] => {
55
+ const parent = parentOf(node);
56
+ return parent === undefined ? [] : [parent, ...ancestorsOf(parent)];
57
+ };
58
+
59
+ const isTypeRead = (node: Node) =>
60
+ isTypeQueryNode(node) || (isImportTypeNode(node) && node.isTypeOf);
61
+
62
+ const identifiersOf = (name: Node) => (isIdentifier(name) ? [name] : nodesIn(name, isIdentifier));
63
+
64
+ const lastIdentifierOf = (name: Node): Identifier | undefined => {
65
+ if (isQualifiedName(name)) {
66
+ return name.right;
67
+ }
68
+ return isIdentifier(name) ? name : undefined;
69
+ };
70
+
71
+ const isInsideItsOwnClass = (reference: Identifier) =>
72
+ ancestorsOf(reference).some(
73
+ (ancestor) => isClassDeclaration(ancestor) && ancestor.name?.text === reference.text,
74
+ );
75
+
76
+ const typeReadIdentifiersIn = (sourceFile: SourceFile) => [
77
+ ...nodesIn(sourceFile, isTypeQueryNode).flatMap((read) => identifiersOf(read.exprName)),
78
+ ...nodesIn(sourceFile, isImportTypeNode).flatMap(({ isTypeOf, qualifier }) => {
79
+ const readsAQualifiedType = isTypeOf && qualifier !== undefined;
80
+ return readsAQualifiedType ? identifiersOf(qualifier) : [];
81
+ }),
82
+ ...nodesIn(sourceFile, isTypeReferenceNode).flatMap(({ typeName }) => {
83
+ const reference = lastIdentifierOf(typeName);
84
+ const isReadFromOutsideItsClass = reference !== undefined && !isInsideItsOwnClass(reference);
85
+ return isReadFromOutsideItsClass ? [reference] : [];
86
+ }),
87
+ ];
88
+
89
+ const renamesIn = (sourceFile: SourceFile) => [
90
+ ...[...nodesIn(sourceFile, isImportSpecifier), ...nodesIn(sourceFile, isExportSpecifier)].flatMap(
91
+ ({ propertyName, name }) => {
92
+ const isRenamed =
93
+ propertyName !== undefined && isIdentifier(propertyName) && isIdentifier(name);
94
+ return isRenamed ? [{ from: propertyName.text, to: name.text }] : [];
95
+ },
96
+ ),
97
+ ...nodesIn(sourceFile, isImportClause).flatMap((clause) =>
98
+ clause.name === undefined ? [] : [{ from: DEFAULT_EXPORT_NAME, to: clause.name.text }],
99
+ ),
100
+ ...nodesIn(sourceFile, isImportEqualsDeclaration).flatMap((declaration) => {
101
+ const target = lastIdentifierOf(declaration.moduleReference);
102
+ return target === undefined ? [] : [{ from: target.text, to: declaration.name.text }];
103
+ }),
104
+ ];
105
+
106
+ const namesAliasing = (
107
+ names: ReadonlySet<string>,
108
+ renames: readonly { readonly from: string; readonly to: string }[],
109
+ ): ReadonlySet<string> => {
110
+ const reached = new Set([
111
+ ...names,
112
+ ...renames.filter(({ from }) => names.has(from)).map(({ to }) => to),
113
+ ]);
114
+ return reached.size === names.size ? names : namesAliasing(reached, renames);
115
+ };
116
+
117
+ const isNamespaceMemberRead = (reference: Identifier) => {
118
+ const { parent } = reference;
119
+ const isMemberAccess =
120
+ isPropertyAccessExpression(parent) &&
121
+ (parent.expression === reference || parent.name === reference);
122
+ const isQualifiedMember =
123
+ isQualifiedName(parent) && (parent.left === reference || parent.right === reference);
124
+ return isMemberAccess || isQualifiedMember;
125
+ };
126
+
127
+ const modulesReadWholeIn = (sourceFile: SourceFile, identifiers: readonly Identifier[]) => {
128
+ const modulesReadWhole = nodesIn(sourceFile, isImportDeclaration).flatMap(
129
+ ({ importClause, moduleSpecifier }) => {
130
+ const namespace = importClause?.namedBindings;
131
+ const isNamespaceImported = namespace !== undefined && isNamespaceImport(namespace);
132
+ if (!isNamespaceImported) {
133
+ return [];
134
+ }
135
+ const isUsedAsValue = identifiers.some(
136
+ (reference) =>
137
+ reference !== namespace.name &&
138
+ reference.text === namespace.name.text &&
139
+ !isNamespaceMemberRead(reference),
140
+ );
141
+ return isUsedAsValue ? [moduleSpecifier] : [];
142
+ },
143
+ );
144
+ const modulesExportedWhole = nodesIn(sourceFile, isExportDeclaration).flatMap(
145
+ ({ exportClause, moduleSpecifier }) => {
146
+ const isExportStarAs =
147
+ exportClause !== undefined &&
148
+ isNamespaceExport(exportClause) &&
149
+ moduleSpecifier !== undefined;
150
+ return isExportStarAs ? [moduleSpecifier] : [];
151
+ },
152
+ );
153
+ const modulesImported = nodesIn(sourceFile, isCallExpression).flatMap(
154
+ ({ expression, arguments: [specifier] }) => {
155
+ const isNamedImport =
156
+ expression.kind === SyntaxKind.ImportKeyword &&
157
+ specifier !== undefined &&
158
+ isStringLiteralLikeNode(specifier);
159
+ return isNamedImport ? [specifier] : [];
160
+ },
161
+ );
162
+ return [...modulesReadWhole, ...modulesExportedWhole, ...modulesImported];
163
+ };
164
+
165
+ const schemaNameOf = (node: Node) => {
166
+ if (isClassDeclaration(node)) {
167
+ return node.name;
168
+ }
169
+ const isNamedConst =
170
+ isVariableDeclaration(node) &&
171
+ isIdentifier(node.name) &&
172
+ (node.parent.flags & NodeFlags.BlockScoped) === NodeFlags.Const;
173
+ return isNamedConst ? node.name : undefined;
174
+ };
175
+
176
+ const handleKeyOf = (declaration: NodeHandle) => `${declaration.path}\0${declaration.index}`;
177
+
178
+ const symbolsAt = (checker: Checker, references: readonly Identifier[]) =>
179
+ resolvedSymbols(checker, references).pipe(
180
+ Effect.flatMap((resolved) =>
181
+ Effect.forEach(references, (reference, index) =>
182
+ valueSymbolAt(checker, reference, Effect.succeed(resolved[index])),
183
+ ),
184
+ ),
185
+ Effect.flatMap((symbols) => followedImportAliases(checker, symbols)),
186
+ );
187
+
188
+ export const findTypeOnlySchemas = (
189
+ projects: Effect.Success<ReturnType<typeof openTypeScriptProjects>>,
190
+ ) =>
191
+ Effect.gen(function* () {
192
+ const files = projects.flatMap(({ checker, allSourceFiles }) =>
193
+ allSourceFiles.map((file) => ({ checker, ...file })),
194
+ );
195
+ const fileAt = new Map(
196
+ projects.flatMap(({ sourceFiles }) =>
197
+ sourceFiles.map((file) => [file.sourceFile.path, file] as const),
198
+ ),
199
+ );
200
+
201
+ const schemasOfEachProject = yield* Effect.forEach(projects, ({ checker, sourceFiles }) =>
202
+ Effect.gen(function* () {
203
+ const typeRead = yield* resolvedSymbols(
204
+ checker,
205
+ sourceFiles.flatMap(({ sourceFile }) => typeReadIdentifiersIn(sourceFile)),
206
+ );
207
+ const variables = [
208
+ ...new Map(
209
+ typeRead.flatMap((symbol) => {
210
+ const declaration = symbol?.valueDeclaration;
211
+ const isProjectVariable =
212
+ symbol !== undefined &&
213
+ declaration !== undefined &&
214
+ (declaration.kind === SyntaxKind.VariableDeclaration ||
215
+ declaration.kind === SyntaxKind.ClassDeclaration) &&
216
+ fileAt.has(declaration.path);
217
+ return isProjectVariable
218
+ ? [[handleKeyOf(declaration), { symbol, declaration }] as const]
219
+ : [];
220
+ }),
221
+ ).values(),
222
+ ];
223
+ const types = yield* typeScriptRequest("read the types of type-read variables", () =>
224
+ checker.getTypeOfSymbol(variables.map(({ symbol }) => symbol)),
225
+ );
226
+ const typed = variables.flatMap((variable, index) => {
227
+ const type = types[index];
228
+ return type === undefined ? [] : [{ ...variable, type }];
229
+ });
230
+ const schemaTypeIds = yield* Effect.forEach(
231
+ typed,
232
+ ({ type }) =>
233
+ typeScriptRequest("read the schema type id", () =>
234
+ checker.getPropertyOfType(type, SCHEMA_TYPE_ID),
235
+ ),
236
+ { concurrency: CONCURRENT_TYPESCRIPT_REQUESTS },
237
+ );
238
+ const declared = yield* Effect.forEach(
239
+ typed.filter((_entry, index) => schemaTypeIds[index] !== undefined),
240
+ ({ declaration }) =>
241
+ typeScriptRequest("read a schema declaration", () => declaration.resolve()).pipe(
242
+ Effect.map((node) => ({ declaration, node })),
243
+ ),
244
+ { concurrency: CONCURRENT_TYPESCRIPT_REQUESTS },
245
+ );
246
+ return declared.flatMap(({ declaration, node }) => {
247
+ const file = fileAt.get(declaration.path);
248
+ const name = node === undefined ? undefined : schemaNameOf(node);
249
+ const isSchemaInTheProject =
250
+ file !== undefined && node !== undefined && name !== undefined;
251
+ if (!isSchemaInTheProject) {
252
+ return [];
253
+ }
254
+ return [
255
+ [
256
+ handleKeyOf(declaration),
257
+ {
258
+ name: name.text,
259
+ location: `${file.displayName}:${nodePosition(file.sourceFile, node).line}`,
260
+ path: declaration.path,
261
+ start: node.pos,
262
+ end: node.end,
263
+ },
264
+ ] as const,
265
+ ];
266
+ });
267
+ }),
268
+ );
269
+ const schemas = new Map(schemasOfEachProject.flat());
270
+
271
+ if (schemas.size === 0) {
272
+ return [];
273
+ }
274
+ const enclosingSchemaOf = (path: string, reference: Node) =>
275
+ [...schemas]
276
+ .filter(
277
+ ([, schema]) =>
278
+ schema.path === path && schema.start <= reference.pos && reference.end <= schema.end,
279
+ )
280
+ .toSorted(([, left], [, right]) => right.start - left.start)
281
+ .map(([key]) => key)
282
+ .at(0);
283
+ const referenceNames = namesAliasing(
284
+ new Set([...schemas.values()].map(({ name }) => name)),
285
+ files.flatMap(({ sourceFile }) => renamesIn(sourceFile)),
286
+ );
287
+ const valueUses = new Map<string, (string | undefined)[]>();
288
+ const readWhole = new Set<string>();
289
+ const identifiersIn = new Map(
290
+ files.map(({ sourceFile }) => [sourceFile, nodesIn(sourceFile, isIdentifier)] as const),
291
+ );
292
+ const modulesReadWholeBy = new Map(
293
+ [...identifiersIn].map(
294
+ ([sourceFile, identifiers]) =>
295
+ [sourceFile, modulesReadWholeIn(sourceFile, identifiers)] as const,
296
+ ),
297
+ );
298
+ for (const { checker, allSourceFiles } of projects) {
299
+ for (const { sourceFile } of allSourceFiles) {
300
+ const references = (identifiersIn.get(sourceFile) ?? []).filter(
301
+ (reference) =>
302
+ referenceNames.has(reference.text) &&
303
+ !(
304
+ (isVariableDeclaration(reference.parent) || isClassDeclaration(reference.parent)) &&
305
+ reference.parent.name === reference
306
+ ),
307
+ );
308
+ if (references.length === 0) {
309
+ continue;
310
+ }
311
+ const symbols = yield* symbolsAt(checker, references);
312
+ for (const [index, reference] of references.entries()) {
313
+ const declaration = symbols[index]?.valueDeclaration;
314
+ const key = declaration === undefined ? undefined : handleKeyOf(declaration);
315
+ const isSchemaReference = key !== undefined && schemas.has(key);
316
+ if (!isSchemaReference) {
317
+ continue;
318
+ }
319
+ const ancestors = ancestorsOf(reference);
320
+ const isAliasOrTypeRead = ancestors.some(
321
+ (node) =>
322
+ isImportDeclaration(node) ||
323
+ isImportEqualsDeclaration(node) ||
324
+ isExportDeclaration(node) ||
325
+ isTypeRead(node) ||
326
+ isTypeReferenceNode(node),
327
+ );
328
+ if (isAliasOrTypeRead) {
329
+ continue;
330
+ }
331
+ valueUses.set(key, [
332
+ ...(valueUses.get(key) ?? []),
333
+ enclosingSchemaOf(sourceFile.path, reference),
334
+ ]);
335
+ }
336
+ }
337
+ const modules = allSourceFiles.flatMap(
338
+ ({ sourceFile }) => modulesReadWholeBy.get(sourceFile) ?? [],
339
+ );
340
+ if (modules.length === 0) {
341
+ continue;
342
+ }
343
+ const moduleSymbols = yield* typeScriptRequest("resolve modules read whole", () =>
344
+ checker.getSymbolAtLocation(modules),
345
+ );
346
+ const moduleExports = yield* Effect.forEach(
347
+ moduleSymbols.filter((symbol) => symbol !== undefined),
348
+ (symbol) =>
349
+ typeScriptRequest("list a module's exports", () => checker.getExportsOfModule(symbol)),
350
+ { concurrency: CONCURRENT_TYPESCRIPT_REQUESTS },
351
+ );
352
+ for (const symbol of yield* followedImportAliases(checker, moduleExports.flat())) {
353
+ if (symbol?.valueDeclaration !== undefined) {
354
+ readWhole.add(handleKeyOf(symbol.valueDeclaration));
355
+ }
356
+ }
357
+ }
358
+
359
+ const keepTypeOnlyUntilStable = (kept: ReadonlySet<string>): ReadonlySet<string> => {
360
+ const stillTypeOnly = new Set(
361
+ [...kept].filter((key) =>
362
+ (valueUses.get(key) ?? []).every(
363
+ (enclosing) => enclosing !== undefined && kept.has(enclosing),
364
+ ),
365
+ ),
366
+ );
367
+ return stillTypeOnly.size === kept.size ? kept : keepTypeOnlyUntilStable(stillTypeOnly);
368
+ };
369
+ const typeOnly = keepTypeOnlyUntilStable(
370
+ new Set([...schemas.keys()].filter((key) => !readWhole.has(key))),
371
+ );
372
+ return [...schemas]
373
+ .filter(([key]) => typeOnly.has(key))
374
+ .map(([, { location, name }]) => new SchemaUsedOnlyAsType({ location, schemaName: name }));
375
+ });
@@ -0,0 +1 @@
1
+ export { findLayerProvidesOutsideProgramStarts } from "./internal/find-layer-provides-outside-program-starts.ts";