@sshkeda/check 0.0.0-stage → 1.0.1

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 +848 -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,357 @@
1
+ import { Effect } from "effect";
2
+ import { SyntaxKind, NodeFlags } from "typescript/unstable/ast";
3
+ import type {
4
+ ArrowFunction,
5
+ Expression,
6
+ FunctionExpression,
7
+ Node,
8
+ SourceFile,
9
+ TypeNode,
10
+ VariableDeclaration,
11
+ } from "typescript/unstable/ast";
12
+ import {
13
+ isArrayLiteralExpression,
14
+ isArrowFunction,
15
+ isCallExpression,
16
+ isFunctionExpression,
17
+ isIdentifier,
18
+ isKeywordTypeNode,
19
+ isLiteralExpression,
20
+ isNewExpression,
21
+ isNoSubstitutionTemplateLiteral,
22
+ isObjectLiteralExpression,
23
+ isPrefixUnaryExpression,
24
+ isPropertyAccessExpression,
25
+ isTemplateExpression,
26
+ isTypePredicateNode,
27
+ isTypeReferenceNode,
28
+ isVariableDeclaration,
29
+ isVariableDeclarationList,
30
+ isVoidExpression,
31
+ } from "typescript/unstable/ast/is";
32
+ import { NodeBuilderFlags } from "typescript/unstable/async";
33
+ import type { Checker, Diagnostic, Program, Type } from "typescript/unstable/async";
34
+
35
+ import {
36
+ nodePosition,
37
+ requiredTypeScriptRequest,
38
+ openTypeScriptProjects,
39
+ typeScriptRequest,
40
+ } from "../../../shared/query-the-typescript-project.ts";
41
+ import {
42
+ InferrableTypeAnnotation,
43
+ InferrableTypeAnnotations,
44
+ SourceOverlayNotApplied,
45
+ } from "./inferrable-annotation-errors.ts";
46
+
47
+ const PRIMITIVE_CONVERSIONS = new Set(["Boolean", "Number", "String", "BigInt", "Symbol"]);
48
+
49
+ const PRIMITIVE_VALUE_NAMES = new Set(["undefined", "Infinity", "NaN"]);
50
+
51
+ const PRIMITIVE_LITERAL_KINDS = new Set([
52
+ SyntaxKind.TrueKeyword,
53
+ SyntaxKind.FalseKeyword,
54
+ SyntaxKind.NullKeyword,
55
+ ]);
56
+
57
+ const callbackOf = (node: Node) => {
58
+ const isFunction = isArrowFunction(node) || isFunctionExpression(node);
59
+ if (!isFunction) {
60
+ return;
61
+ }
62
+ const call = node.parent;
63
+ const isPassedToACall =
64
+ (isCallExpression(call) || isNewExpression(call)) &&
65
+ (call.arguments ?? []).some((argument) => argument === node);
66
+ return isPassedToACall ? node : undefined;
67
+ };
68
+
69
+ const calleeName = (callback: ArrowFunction | FunctionExpression) => {
70
+ const call = callback.parent;
71
+ const isCallOrConstruction = isCallExpression(call) || isNewExpression(call);
72
+ const callee = isCallOrConstruction ? call.expression : call;
73
+ if (isIdentifier(callee)) {
74
+ return callee.text;
75
+ }
76
+ return isPropertyAccessExpression(callee) ? callee.name.text : "a call";
77
+ };
78
+
79
+ const isPrimitiveAnnotation = (annotation: TypeNode) =>
80
+ isKeywordTypeNode(annotation) ||
81
+ annotation.kind === SyntaxKind.LiteralType ||
82
+ (isTypeReferenceNode(annotation) &&
83
+ isIdentifier(annotation.typeName) &&
84
+ annotation.typeName.text === "RegExp");
85
+
86
+ const isPrimitiveInitializer = (initializer: Expression) =>
87
+ isLiteralExpression(initializer) ||
88
+ isNoSubstitutionTemplateLiteral(initializer) ||
89
+ isTemplateExpression(initializer) ||
90
+ isPrefixUnaryExpression(initializer) ||
91
+ isVoidExpression(initializer) ||
92
+ PRIMITIVE_LITERAL_KINDS.has(initializer.kind) ||
93
+ (isIdentifier(initializer) && PRIMITIVE_VALUE_NAMES.has(initializer.text)) ||
94
+ (isCallExpression(initializer) &&
95
+ isIdentifier(initializer.expression) &&
96
+ PRIMITIVE_CONVERSIONS.has(initializer.expression.text));
97
+
98
+ const isFilledLiteral = (initializer: Expression) =>
99
+ (isObjectLiteralExpression(initializer) && initializer.properties.length > 0) ||
100
+ (isArrayLiteralExpression(initializer) && initializer.elements.length > 0);
101
+
102
+ const constantAnnotationOf = (node: Node) => {
103
+ if (!isVariableDeclaration(node)) {
104
+ return;
105
+ }
106
+ const { type, initializer, name, parent } = node;
107
+ const isAnnotatedIdentifierWithInitializer =
108
+ type !== undefined && initializer !== undefined && isIdentifier(name);
109
+ if (!isAnnotatedIdentifierWithInitializer) {
110
+ return;
111
+ }
112
+ const isInferrable =
113
+ isVariableDeclarationList(parent) &&
114
+ (parent.flags & NodeFlags.BlockScoped) === NodeFlags.Const &&
115
+ (parent.flags & NodeFlags.Ambient) === 0 &&
116
+ !isFilledLiteral(initializer) &&
117
+ !(isPrimitiveAnnotation(type) && isPrimitiveInitializer(initializer));
118
+ return isInferrable
119
+ ? {
120
+ annotation: type,
121
+ fact: `${name.text} has a type annotation TypeScript can infer`,
122
+ edit: { start: name.end, end: type.end, replacement: "" },
123
+ }
124
+ : undefined;
125
+ };
126
+
127
+ const callbackAnnotationOf = (node: Node) => {
128
+ const callback = callbackOf(node);
129
+ const annotation = callback?.type;
130
+ const isInferrable =
131
+ callback !== undefined && annotation !== undefined && !isTypePredicateNode(annotation);
132
+ return isInferrable
133
+ ? {
134
+ annotation,
135
+ fact: `the callback passed to ${calleeName(callback)} has a return type annotation TypeScript can infer`,
136
+ edit: { start: callback.parameters.end, end: annotation.end, replacement: ")" },
137
+ }
138
+ : undefined;
139
+ };
140
+
141
+ const annotationOf = (node: Node) => constantAnnotationOf(node) ?? callbackAnnotationOf(node);
142
+
143
+ const annotatableNodesByStart = (sourceFile: SourceFile) => {
144
+ const found = new Map<number, ArrowFunction | FunctionExpression | VariableDeclaration>();
145
+ const visit = (node: Node): void => {
146
+ const annotatable = isVariableDeclaration(node) ? node : callbackOf(node);
147
+ if (annotatable !== undefined) {
148
+ found.set(node.getStart(sourceFile), annotatable);
149
+ }
150
+ node.forEachChild(visit);
151
+ };
152
+ sourceFile.forEachChild(visit);
153
+ return found;
154
+ };
155
+
156
+ const FULL_TYPE_TEXT = NodeBuilderFlags.NoTruncation | NodeBuilderFlags.UseFullyQualifiedType;
157
+
158
+ const typeText = (checker: Checker, type: Type) =>
159
+ typeScriptRequest("print a type", () => checker.typeToString(type, undefined, FULL_TYPE_TEXT));
160
+
161
+ const candidatesIn = (
162
+ checker: Checker,
163
+ {
164
+ sourceFile,
165
+ displayName,
166
+ }: Effect.Success<ReturnType<typeof openTypeScriptProjects>>[number]["sourceFiles"][number],
167
+ ) =>
168
+ Effect.forEach(annotatableNodesByStart(sourceFile), ([start, node]) =>
169
+ Effect.gen(function* () {
170
+ const annotated = annotationOf(node);
171
+ if (annotated === undefined) {
172
+ return [];
173
+ }
174
+ const annotatedType = yield* requiredTypeScriptRequest("read an annotated type", () =>
175
+ checker.getTypeFromTypeNode(annotated.annotation),
176
+ );
177
+ return [
178
+ {
179
+ ...annotated,
180
+ sourceFile,
181
+ displayName,
182
+ start,
183
+ annotatedTypeText: yield* typeText(checker, annotatedType),
184
+ },
185
+ ];
186
+ }),
187
+ ).pipe(Effect.map((candidates) => candidates.flat()));
188
+
189
+ const shiftBefore = (
190
+ candidates: readonly Effect.Success<ReturnType<typeof candidatesIn>>[number][],
191
+ position: number,
192
+ ) =>
193
+ candidates
194
+ .filter((candidate) => candidate.edit.end <= position)
195
+ .reduce((total, { edit }) => total + edit.end - edit.start - edit.replacement.length, 0);
196
+
197
+ const textWithoutAnnotations = (
198
+ text: string,
199
+ candidates: readonly Effect.Success<ReturnType<typeof candidatesIn>>[number][],
200
+ ) =>
201
+ candidates
202
+ .toSorted((first, second) => second.edit.start - first.edit.start)
203
+ .reduce(
204
+ (remaining, { edit }) =>
205
+ remaining.slice(0, edit.start) + edit.replacement + remaining.slice(edit.end),
206
+ text,
207
+ );
208
+
209
+ const typeScriptViolationsOf = (program: Program, fileName: string) =>
210
+ Effect.gen(function* () {
211
+ const semantic = yield* typeScriptRequest("read semantic diagnostics", () =>
212
+ program.getSemanticDiagnostics(fileName),
213
+ );
214
+ const declaration = yield* typeScriptRequest("read declaration diagnostics", () =>
215
+ program.getDeclarationDiagnostics(fileName),
216
+ );
217
+ return [...semantic, ...declaration];
218
+ });
219
+
220
+ const violationKey = (fileName: string, violation: Diagnostic) =>
221
+ [fileName, violation.code, violation.text].join("\n");
222
+
223
+ const inferredType = (
224
+ checker: Checker,
225
+ node: ArrowFunction | FunctionExpression | VariableDeclaration,
226
+ ) =>
227
+ Effect.gen(function* () {
228
+ if (isVariableDeclaration(node)) {
229
+ return yield* requiredTypeScriptRequest("read an inferred type", () =>
230
+ checker.getTypeAtLocation(node.name),
231
+ );
232
+ }
233
+ const signature = yield* requiredTypeScriptRequest("read a callback signature", () =>
234
+ checker.getSignatureFromDeclaration(node),
235
+ );
236
+ return yield* requiredTypeScriptRequest("read an inferred return type", () =>
237
+ checker.getReturnTypeOfSignature(signature),
238
+ );
239
+ });
240
+
241
+ const annotationsStillNeeded = <CountingError>(
242
+ projectFile: string,
243
+ candidates: readonly Effect.Success<ReturnType<typeof candidatesIn>>[number][],
244
+ countBaselineViolations: Effect.Effect<ReadonlyMap<string, number>, CountingError>,
245
+ ) =>
246
+ Effect.gen(function* () {
247
+ const candidatesOfSourceFile = Map.groupBy(candidates, (candidate) => candidate.sourceFile);
248
+ const candidatesOfFile = new Map(
249
+ Array.from(candidatesOfSourceFile, ([sourceFile, fileCandidates]) => [
250
+ sourceFile.fileName,
251
+ fileCandidates,
252
+ ]),
253
+ );
254
+ const sourceTextOverrides = new Map(
255
+ Array.from(candidatesOfSourceFile, ([sourceFile, fileCandidates]) => [
256
+ sourceFile.fileName,
257
+ textWithoutAnnotations(sourceFile.text, fileCandidates),
258
+ ]),
259
+ );
260
+ const needed = new Set<(typeof candidates)[number]>();
261
+ const strippedProjects = yield* openTypeScriptProjects(projectFile, sourceTextOverrides);
262
+ for (const { checker, sourceFiles } of strippedProjects) {
263
+ for (const { sourceFile } of sourceFiles) {
264
+ const override = sourceTextOverrides.get(sourceFile.fileName);
265
+ const isOverrideMissingFromProgram = override !== undefined && override !== sourceFile.text;
266
+ if (isOverrideMissingFromProgram) {
267
+ return yield* new SourceOverlayNotApplied({ fileName: sourceFile.fileName });
268
+ }
269
+ const fileCandidates = candidatesOfFile.get(sourceFile.fileName) ?? [];
270
+ const annotatable = annotatableNodesByStart(sourceFile);
271
+ for (const candidate of fileCandidates) {
272
+ const node = annotatable.get(
273
+ candidate.start - shiftBefore(fileCandidates, candidate.start),
274
+ );
275
+ const isMissingOrStillAnnotated = node === undefined || node.type !== undefined;
276
+ if (isMissingOrStillAnnotated) {
277
+ return yield* new SourceOverlayNotApplied({ fileName: sourceFile.fileName });
278
+ }
279
+ const strippingChangedType =
280
+ (yield* typeText(checker, yield* inferredType(checker, node))) !==
281
+ candidate.annotatedTypeText;
282
+ if (strippingChangedType) {
283
+ needed.add(candidate);
284
+ }
285
+ }
286
+ }
287
+ }
288
+ if (needed.size === candidates.length) {
289
+ return needed;
290
+ }
291
+ const remainingBaseline = new Map(yield* countBaselineViolations);
292
+ for (const { program, sourceFiles } of strippedProjects) {
293
+ for (const { sourceFile } of sourceFiles) {
294
+ const fileCandidates = candidatesOfFile.get(sourceFile.fileName) ?? [];
295
+ const newViolations = (yield* typeScriptViolationsOf(program, sourceFile.fileName)).filter(
296
+ (violation) => {
297
+ const key = violationKey(sourceFile.fileName, violation);
298
+ const baselineCount = remainingBaseline.get(key) ?? 0;
299
+ remainingBaseline.set(key, baselineCount - 1);
300
+ return baselineCount <= 0;
301
+ },
302
+ );
303
+ if (newViolations.length > 0) {
304
+ for (const candidate of fileCandidates.length > 0 ? fileCandidates : candidates) {
305
+ needed.add(candidate);
306
+ }
307
+ }
308
+ }
309
+ }
310
+ return needed;
311
+ }).pipe(Effect.scoped);
312
+
313
+ export const findInferrableAnnotations = <OpeningError, OpeningRequirement>(
314
+ projectFile: string,
315
+ openedProjects: Effect.Effect<
316
+ Effect.Success<ReturnType<typeof openTypeScriptProjects>>,
317
+ OpeningError,
318
+ OpeningRequirement
319
+ >,
320
+ ) =>
321
+ Effect.gen(function* () {
322
+ const projects = yield* openedProjects;
323
+ const annotated: Effect.Success<ReturnType<typeof candidatesIn>>[number][] = [];
324
+ for (const { checker, sourceFiles } of projects) {
325
+ for (const projectSourceFile of sourceFiles) {
326
+ annotated.push(...(yield* candidatesIn(checker, projectSourceFile)));
327
+ }
328
+ }
329
+ if (annotated.length === 0) {
330
+ return;
331
+ }
332
+ const countBaselineViolations = Effect.gen(function* () {
333
+ const counts = new Map<string, number>();
334
+ for (const { program, sourceFiles } of projects) {
335
+ for (const { sourceFile } of sourceFiles) {
336
+ for (const violation of yield* typeScriptViolationsOf(program, sourceFile.fileName)) {
337
+ const key = violationKey(sourceFile.fileName, violation);
338
+ counts.set(key, (counts.get(key) ?? 0) + 1);
339
+ }
340
+ }
341
+ }
342
+ return counts;
343
+ });
344
+ const needed = yield* annotationsStillNeeded(projectFile, annotated, countBaselineViolations);
345
+ const violations = annotated
346
+ .filter((candidate) => !needed.has(candidate))
347
+ .map((candidate) => {
348
+ const location = nodePosition(candidate.sourceFile, candidate.annotation);
349
+ return new InferrableTypeAnnotation({
350
+ location: `${candidate.displayName}:${location.line}:${location.column}`,
351
+ fact: candidate.fact,
352
+ });
353
+ });
354
+ if (violations.length > 0) {
355
+ return yield* new InferrableTypeAnnotations({ violations });
356
+ }
357
+ }).pipe(Effect.scoped);
@@ -0,0 +1,33 @@
1
+ import { Schema } from "effect";
2
+
3
+ import { listedViolations } from "../../../../../shared/format-reported-failures.ts";
4
+
5
+ export class InferrableTypeAnnotation extends Schema.TaggedError<InferrableTypeAnnotation>()(
6
+ "InferrableTypeAnnotation",
7
+ {
8
+ location: Schema.String,
9
+ fact: Schema.String,
10
+ },
11
+ ) {
12
+ public override get message() {
13
+ return this.fact;
14
+ }
15
+ }
16
+
17
+ export class InferrableTypeAnnotations extends Schema.TaggedError<InferrableTypeAnnotations>()(
18
+ "InferrableTypeAnnotations",
19
+ { violations: Schema.Array(InferrableTypeAnnotation) },
20
+ ) {
21
+ public override get message() {
22
+ return listedViolations(this.violations);
23
+ }
24
+ }
25
+
26
+ export class SourceOverlayNotApplied extends Schema.TaggedError<SourceOverlayNotApplied>()(
27
+ "SourceOverlayNotApplied",
28
+ { fileName: Schema.String },
29
+ ) {
30
+ public override get message() {
31
+ return `the TypeScript API checked ${this.fileName} without its type annotations removed`;
32
+ }
33
+ }
@@ -0,0 +1 @@
1
+ export { findRepeatedServiceYields } from "./internal/find-repeated-service-yields.ts";
@@ -0,0 +1,162 @@
1
+ import { Array as Arrays, Effect } from "effect";
2
+ import type { Node, SourceFile } from "typescript/unstable/ast";
3
+ import {
4
+ isFunctionLikeDeclaration,
5
+ isIdentifier,
6
+ isParenthesizedExpression,
7
+ isPropertyAccessExpression,
8
+ isYieldExpression,
9
+ } from "typescript/unstable/ast/is";
10
+ import { SymbolFlags } from "typescript/unstable/async";
11
+ import type { Checker, Symbol as CheckerSymbol } from "typescript/unstable/async";
12
+
13
+ import {
14
+ nodePosition,
15
+ resolvedSymbols,
16
+ typeScriptRequest,
17
+ } from "../../../shared/query-the-typescript-project.ts";
18
+ import type { openTypeScriptProjects } from "../../../shared/query-the-typescript-project.ts";
19
+ import { RepeatedServiceYield, RepeatedServiceYields } from "./repeated-service-yield-errors.ts";
20
+
21
+ const SERVICE_PROPERTIES = ["~effect/Context/Service", "key", "Service", "Identifier"] as const;
22
+
23
+ const yieldedReference = (node: Node): Node | undefined => {
24
+ if (isParenthesizedExpression(node)) {
25
+ return yieldedReference(node.expression);
26
+ }
27
+ if (isIdentifier(node)) {
28
+ return node;
29
+ }
30
+ if (isPropertyAccessExpression(node)) {
31
+ return node.name;
32
+ }
33
+ return undefined;
34
+ };
35
+
36
+ const generatorYieldGroups = (sourceFile: SourceFile) => {
37
+ const groups: (readonly { readonly yieldExpression: Node; readonly reference: Node }[])[] = [];
38
+ const visit = (node: Node, serviceYields?: (typeof groups)[number][number][]): void => {
39
+ if (isFunctionLikeDeclaration(node)) {
40
+ const isGeneratorWithBody = node.asteriskToken !== undefined && node.body !== undefined;
41
+ if (isGeneratorWithBody) {
42
+ node.forEachChild((child) => {
43
+ if (child !== node.body) {
44
+ visit(child);
45
+ }
46
+ });
47
+ const generatorYields: (typeof groups)[number][number][] = [];
48
+ node.body.forEachChild((child) => {
49
+ visit(child, generatorYields);
50
+ });
51
+ if (generatorYields.length > 1) {
52
+ groups.push(generatorYields);
53
+ }
54
+ return;
55
+ }
56
+ node.forEachChild((child) => {
57
+ visit(child);
58
+ });
59
+ return;
60
+ }
61
+ const isDelegatingYieldWithOperand =
62
+ serviceYields !== undefined &&
63
+ isYieldExpression(node) &&
64
+ node.asteriskToken !== undefined &&
65
+ node.expression !== undefined;
66
+ if (isDelegatingYieldWithOperand) {
67
+ const reference = yieldedReference(node.expression);
68
+ if (reference) {
69
+ serviceYields.push({ yieldExpression: node, reference });
70
+ }
71
+ }
72
+ node.forEachChild((child) => {
73
+ visit(child, serviceYields);
74
+ });
75
+ };
76
+ sourceFile.forEachChild((child) => {
77
+ visit(child);
78
+ });
79
+ return groups;
80
+ };
81
+
82
+ const serviceTag = (checker: Checker, symbol: CheckerSymbol) =>
83
+ Effect.gen(function* () {
84
+ if ((symbol.flags & (SymbolFlags.Class | SymbolFlags.Variable)) === 0) {
85
+ return false;
86
+ }
87
+ const symbolType = yield* typeScriptRequest("read a service type", () =>
88
+ checker.getTypeOfSymbol(symbol),
89
+ );
90
+ if (symbolType === undefined) {
91
+ return false;
92
+ }
93
+ const properties = yield* Effect.forEach(SERVICE_PROPERTIES, (property) =>
94
+ typeScriptRequest("read a service property", () =>
95
+ checker.getPropertyOfType(symbolType, property),
96
+ ),
97
+ );
98
+ return properties.every((property) => property !== undefined);
99
+ });
100
+
101
+ const fileViolations = (
102
+ checker: Checker,
103
+ sourceFile: SourceFile,
104
+ displayName: string,
105
+ serviceTags: Map<number, boolean>,
106
+ ) =>
107
+ Effect.gen(function* () {
108
+ const violations: RepeatedServiceYield[] = [];
109
+ for (const serviceYields of generatorYieldGroups(sourceFile)) {
110
+ const symbols = yield* resolvedSymbols(
111
+ checker,
112
+ serviceYields.map((serviceYield) => serviceYield.reference),
113
+ );
114
+ const firstYields = new Map<number, Node>();
115
+ for (const [symbol, serviceYield] of Arrays.zip(symbols, serviceYields)) {
116
+ if (symbol === undefined) {
117
+ continue;
118
+ }
119
+ const firstYield = firstYields.get(symbol.id);
120
+ if (firstYield === undefined) {
121
+ firstYields.set(symbol.id, serviceYield.yieldExpression);
122
+ continue;
123
+ }
124
+ const isServiceTag = serviceTags.get(symbol.id) ?? (yield* serviceTag(checker, symbol));
125
+ serviceTags.set(symbol.id, isServiceTag);
126
+ if (!isServiceTag) {
127
+ continue;
128
+ }
129
+ const repeated = nodePosition(sourceFile, serviceYield.yieldExpression);
130
+ const first = nodePosition(sourceFile, firstYield);
131
+ violations.push(
132
+ new RepeatedServiceYield({
133
+ location: `${displayName}:${repeated.line}:${repeated.column}`,
134
+ service: symbol.name,
135
+ firstYield: `${first.line}:${first.column}`,
136
+ }),
137
+ );
138
+ }
139
+ }
140
+ return violations;
141
+ });
142
+
143
+ export const findRepeatedServiceYields = <OpeningError, OpeningRequirement>(
144
+ _projectFile: string,
145
+ openedProjects: Effect.Effect<
146
+ Effect.Success<ReturnType<typeof openTypeScriptProjects>>,
147
+ OpeningError,
148
+ OpeningRequirement
149
+ >,
150
+ ) =>
151
+ Effect.gen(function* () {
152
+ const serviceTags = new Map<number, boolean>();
153
+ const violations: RepeatedServiceYield[] = [];
154
+ for (const { checker, sourceFiles } of yield* openedProjects) {
155
+ for (const { sourceFile, displayName } of sourceFiles) {
156
+ violations.push(...(yield* fileViolations(checker, sourceFile, displayName, serviceTags)));
157
+ }
158
+ }
159
+ if (violations.length > 0) {
160
+ return yield* new RepeatedServiceYields({ violations });
161
+ }
162
+ }).pipe(Effect.scoped);
@@ -0,0 +1,25 @@
1
+ import { Schema } from "effect";
2
+
3
+ import { listedViolations } from "../../../../../shared/format-reported-failures.ts";
4
+
5
+ export class RepeatedServiceYield extends Schema.TaggedError<RepeatedServiceYield>()(
6
+ "RepeatedServiceYield",
7
+ {
8
+ location: Schema.String,
9
+ service: Schema.String,
10
+ firstYield: Schema.String,
11
+ },
12
+ ) {
13
+ public override get message() {
14
+ return `service ${this.service} was already yielded at ${this.firstYield}`;
15
+ }
16
+ }
17
+
18
+ export class RepeatedServiceYields extends Schema.TaggedError<RepeatedServiceYields>()(
19
+ "RepeatedServiceYields",
20
+ { violations: Schema.Array(RepeatedServiceYield) },
21
+ ) {
22
+ public override get message() {
23
+ return listedViolations(this.violations);
24
+ }
25
+ }
@@ -0,0 +1,5 @@
1
+ import { Task } from "@sshkeda/task";
2
+
3
+ import { fileLayoutViolationsOfEachPackage } from "./internal/check-the-layout-of-each-package.ts";
4
+
5
+ export const layout = Task.make("layout", fileLayoutViolationsOfEachPackage);
@@ -0,0 +1,9 @@
1
+ import { inEachPackage } from "../../../shared/check-each-nested-package.ts";
2
+ import { quietViolations } from "../../../shared/print-failures-and-keep-detail-in-the-trace.ts";
3
+ import { findFileLayoutViolations } from "./find-file-layout-violations.ts";
4
+
5
+ const LAYOUT = "layout";
6
+
7
+ export const fileLayoutViolationsOfEachPackage = inEachPackage(LAYOUT, ".", (packageDirectory) =>
8
+ findFileLayoutViolations(packageDirectory).pipe(quietViolations(LAYOUT)),
9
+ );