@autotelic/plumb 0.3.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 (94) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +64 -0
  3. package/package.json +41 -0
  4. package/src/effect/index.ts +59 -0
  5. package/src/effect/rules/guarded-op-must-return-effect.ts +236 -0
  6. package/src/effect/rules/guarded-op-must-return-option.ts +97 -0
  7. package/src/effect/rules/no-cascading-layer-provide.ts +80 -0
  8. package/src/effect/rules/no-decode-unknown-option.ts +41 -0
  9. package/src/effect/rules/no-direct-browser-storage.ts +91 -0
  10. package/src/effect/rules/no-direct-fetch.ts +44 -0
  11. package/src/effect/rules/no-manual-field-guards.ts +144 -0
  12. package/src/effect/rules/no-nested-layer-provide.ts +51 -0
  13. package/src/effect/rules/no-schema-class-modeling.ts +59 -0
  14. package/src/effect/rules/no-service-constructor-imports.ts +50 -0
  15. package/src/effect/rules/no-silent-error-swallow.ts +99 -0
  16. package/src/effect/rules/no-static-effect-service-forwarders.ts +227 -0
  17. package/src/effect/rules/no-try-catch.ts +32 -0
  18. package/src/effect/rules/no-unguarded-json-parse.ts +211 -0
  19. package/src/effect/rules/option-core-needs-effect-public.ts +81 -0
  20. package/src/effect/rules/prefer-die-for-precondition-defects.ts +118 -0
  21. package/src/effect/rules/prefer-effect-gen-for-guard-ladders.ts +76 -0
  22. package/src/effect/rules/prefer-effect-match.ts +78 -0
  23. package/src/effect/rules/prefer-effect-predicate-over-boolean-function.ts +79 -0
  24. package/src/effect/rules/prefer-named-guard-predicate.ts +105 -0
  25. package/src/effect/rules/prefer-option-pipeline.ts +95 -0
  26. package/src/effect/rules/prefer-ordering-match.ts +152 -0
  27. package/src/effect/rules/prefer-tagged-enum.ts +68 -0
  28. package/src/effect/rules/require-schema-type-derivation.ts +83 -0
  29. package/src/index.ts +106 -0
  30. package/src/meta/index.ts +25 -0
  31. package/src/meta/rules/no-disable-directives.ts +38 -0
  32. package/src/meta/rules/no-manual-ancestor-walks.ts +27 -0
  33. package/src/meta/rules/prefer-before-file-scope.ts +57 -0
  34. package/src/meta/rules/require-create-once.ts +51 -0
  35. package/src/meta/rules/require-rule-tester.ts +57 -0
  36. package/src/rules/no-anonymous-wide-tuples.ts +38 -0
  37. package/src/rules/no-barrel-export-star.ts +30 -0
  38. package/src/rules/no-boolean-field-signals.ts +305 -0
  39. package/src/rules/no-builtin-throws.ts +83 -0
  40. package/src/rules/no-chained-type-assertions.ts +65 -0
  41. package/src/rules/no-conditional-empty-object-spread.ts +42 -0
  42. package/src/rules/no-duplicated-literal-union.ts +66 -0
  43. package/src/rules/no-exported-mutable-state.ts +111 -0
  44. package/src/rules/no-generic-export-names.ts +149 -0
  45. package/src/rules/no-impossible-branch-throw.ts +55 -0
  46. package/src/rules/no-known-value-widening.ts +225 -0
  47. package/src/rules/no-module-mocking.ts +95 -0
  48. package/src/rules/no-multiple-function-params.ts +192 -0
  49. package/src/rules/no-nondeterministic-core.ts +73 -0
  50. package/src/rules/no-object-parameters.ts +127 -0
  51. package/src/rules/no-optional-function-parameters.ts +49 -0
  52. package/src/rules/no-product-of-state-booleans.ts +80 -0
  53. package/src/rules/no-redundant-derived-field.ts +192 -0
  54. package/src/rules/no-reflect-apply.ts +32 -0
  55. package/src/rules/no-reflect-get.ts +32 -0
  56. package/src/rules/no-reinterpret-cast.ts +78 -0
  57. package/src/rules/no-runtime-typeof.ts +59 -0
  58. package/src/rules/no-sentinel-comparison-union.ts +148 -0
  59. package/src/rules/no-shape-in-symbol-names.ts +45 -0
  60. package/src/rules/no-single-use-private-functions.ts +329 -0
  61. package/src/rules/no-stacked-jsdoc-blocks.ts +65 -0
  62. package/src/rules/no-stray-inline-comments.ts +79 -0
  63. package/src/rules/no-swappable-primitive-params.ts +109 -0
  64. package/src/rules/no-tag-ladder-assertions.ts +71 -0
  65. package/src/rules/no-transposed-field-reads.ts +135 -0
  66. package/src/rules/no-unit-return-validators.ts +65 -0
  67. package/src/rules/no-unknown-parameters.ts +97 -0
  68. package/src/rules/no-unknown-returns.ts +120 -0
  69. package/src/rules/no-unknown-type-aliases.ts +70 -0
  70. package/src/rules/no-unsafe-dictionary-type.ts +132 -0
  71. package/src/rules/no-vague-test-filenames.ts +67 -0
  72. package/src/rules/no-widen-then-assert.ts +345 -0
  73. package/src/rules/prefer-payload-brand.ts +67 -0
  74. package/src/rules/prefer-property-tests.ts +43 -0
  75. package/src/rules/require-canonical-stringify-for-identity.ts +80 -0
  76. package/src/rules/require-deprecated-tag-for-legacy-comments.ts +45 -0
  77. package/src/rules/require-exhaustive-tag-switch.ts +42 -0
  78. package/src/rules/require-fc-block-predicate.ts +42 -0
  79. package/src/rules/require-jsdoc-on-exported.ts +74 -0
  80. package/src/rules/require-published-order.ts +109 -0
  81. package/src/rules/require-safety-comment-for-type-assertion.ts +61 -0
  82. package/src/rules/require-sort-comparator.ts +41 -0
  83. package/src/rules/test-utils.ts +68 -0
  84. package/src/shared/ancestors.ts +21 -0
  85. package/src/shared/child-nodes.ts +27 -0
  86. package/src/shared/dictionary-types.ts +524 -0
  87. package/src/shared/is-node.ts +13 -0
  88. package/src/shared/lexical-type-parameters.ts +62 -0
  89. package/src/shared/reflect-method.ts +41 -0
  90. package/src/shared/rule-options.ts +23 -0
  91. package/src/shared/structural.ts +81 -0
  92. package/src/testing/index.ts +3 -0
  93. package/src/testing/testable-rule.test.ts +68 -0
  94. package/src/testing/testable-rule.ts +86 -0
@@ -0,0 +1,227 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+
3
+ import type { ESTree, SourceCode } from "@oxlint/plugins";
4
+
5
+ import { ancestorsOf } from "../../shared/ancestors.ts";
6
+
7
+ import { isString } from "../../shared/structural.ts";
8
+
9
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$|\/test\//u;
10
+
11
+ interface CallbackExpression {
12
+ expression: ESTree.Node;
13
+ parameterName: string | undefined;
14
+ }
15
+
16
+ /** Computed or plain property name on a member expression.
17
+ *
18
+ * @param {ESTree.MemberExpression} member - The member expression node.
19
+ * @returns {string | null} The property name, or null when unavailable.
20
+ */
21
+ function memberName(member: ESTree.MemberExpression): string | null {
22
+ if (!member.computed) {
23
+ return member.property.type === "Identifier" ? member.property.name : null;
24
+ }
25
+ if (member.property.type === "Literal" && isString(member.property.value)) {
26
+ return member.property.value;
27
+ }
28
+ return null;
29
+ }
30
+
31
+ /** Imported name behind an import specifier, for both plain and string-literal spellings.
32
+ *
33
+ * @param {ESTree.Node} specifier - The import specifier node.
34
+ * @returns {string | undefined} The imported name, if any.
35
+ */
36
+ function importedNameOf(specifier: ESTree.Node): string | undefined {
37
+ if (specifier.type !== "ImportSpecifier") return undefined;
38
+ return specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
39
+ }
40
+
41
+ /** Local binding name of an import specifier.
42
+ *
43
+ * @param {ESTree.Node} specifier - The import specifier node.
44
+ * @returns {string | undefined} The local bound name, if any.
45
+ */
46
+ function localNameOf(specifier: ESTree.Node): string | undefined {
47
+ return specifier.type === "ImportSpecifier" || specifier.type === "ImportNamespaceSpecifier"
48
+ ? specifier.local.name
49
+ : undefined;
50
+ }
51
+
52
+ /** Whether the call site sits inside a `static` class property initializer.
53
+ *
54
+ * @param {SourceCode} sourceCode - The rule's source-code accessor.
55
+ * @param {ESTree.Node} node - The call expression being visited.
56
+ * @returns {boolean} True when enclosed by a static property definition.
57
+ */
58
+ function inStaticClassField(sourceCode: SourceCode, node: ESTree.Node): boolean {
59
+ for (const current of ancestorsOf(sourceCode, node)) {
60
+ if (current.type === "PropertyDefinition") return current.static === true;
61
+ if (current.type === "Program") return false;
62
+ }
63
+ return false;
64
+ }
65
+
66
+ /**
67
+ * Single-parameter handler whose body is one expression or one return statement.
68
+ *
69
+ * @param {ESTree.Node} node - The candidate callback function node.
70
+ * @returns {CallbackExpression | undefined} The extracted expression and parameter, if matching.
71
+ */
72
+ function callbackExpression(node: ESTree.Node): CallbackExpression | undefined {
73
+ if (node.type !== "ArrowFunctionExpression" && node.type !== "FunctionExpression") return undefined;
74
+ if (node.params.length !== 1) return undefined;
75
+ const parameter = node.params[0]!;
76
+ if (parameter.type !== "Identifier") return undefined;
77
+ const parameterName = parameter.name;
78
+ if (node.body === null) return undefined;
79
+ let body: ESTree.Node = node.body;
80
+ if (body.type === "BlockStatement") {
81
+ if (body.body.length !== 1) return undefined;
82
+ const statement = body.body[0]!;
83
+ if (statement.type !== "ReturnStatement") return undefined;
84
+ if (statement.argument === null || statement.argument === undefined) return undefined;
85
+ body = statement.argument;
86
+ }
87
+ return { expression: body, parameterName };
88
+ }
89
+
90
+ /** `svc.member(...)` or bare `svc.member`, where `svc` is exactly the acquired service.
91
+ *
92
+ * @param {ESTree.Expression} expression - The forwarded callback expression.
93
+ * @param {string | undefined} parameterName - The acquired service parameter name.
94
+ * @returns {boolean} True when the expression only reads that service's member.
95
+ */
96
+ function isDirectParameterMember(expression: ESTree.Node, parameterName: string | undefined): boolean {
97
+ if (parameterName === undefined) return false;
98
+ const member =
99
+ expression.type === "CallExpression" ? expression.callee : expression;
100
+ if (member.type !== "MemberExpression") return false;
101
+ return member.object.type === "Identifier" && member.object.name === parameterName;
102
+ }
103
+
104
+ /** Static forwarders alias a service method at module scope; acquire the service where its method is used instead.
105
+ *
106
+ * Import tracking covers local names bound by imports of "effect" and
107
+ * "effect/Effect"; re-exports are not tracked.
108
+ */
109
+ export const noStaticEffectServiceForwardersRule = defineRule({
110
+ meta: {
111
+ type: "problem",
112
+ docs: {
113
+ description:
114
+ "Disallow static class-field forwarders around Effect services; yield the service at the usage site and call the method directly so dependencies stay explicit.",
115
+ },
116
+ messages: {
117
+ staticForwarder:
118
+ "This static field forwards an Effect service method. Acquire the service where the method is used (`Effect.flatMap(Service, (svc) => ...)`) so the dependency stays explicit and testable.",
119
+ },
120
+ },
121
+ createOnce(context) {
122
+ const effectNamespaceNames = new Set<string>();
123
+ const flatMapNames = new Set<string>();
124
+ const serviceNames = new Set<string>();
125
+ const pipeNames = new Set<string>();
126
+
127
+ const isEffectCall = (
128
+ node: ESTree.Node,
129
+ method: string,
130
+ directNames: ReadonlySet<string>,
131
+ ): node is ESTree.CallExpression => {
132
+ if (node.type !== "CallExpression") return false;
133
+ const callee = node.callee;
134
+ if (callee.type === "Identifier") {
135
+ return directNames.has(callee.name);
136
+ }
137
+ if (callee.type !== "MemberExpression") return false;
138
+ return (
139
+ callee.object.type === "Identifier" &&
140
+ effectNamespaceNames.has(callee.object.name) &&
141
+ memberName(callee) === method
142
+ );
143
+ };
144
+
145
+ const isServiceAcquisition = (node: ESTree.Node): boolean => {
146
+ if (!isEffectCall(node, "service", serviceNames)) return false;
147
+ return node.arguments.length === 1 && node.arguments[0]!.type === "ThisExpression";
148
+ };
149
+
150
+ const isForwardingFlatMap = (node: ESTree.Node): boolean => {
151
+ if (!isEffectCall(node, "flatMap", flatMapNames)) return false;
152
+ const last = node.arguments[node.arguments.length - 1];
153
+ if (last === undefined) return false;
154
+ const callback = callbackExpression(last);
155
+ if (callback === undefined) return false;
156
+ return isDirectParameterMember(callback.expression, callback.parameterName);
157
+ };
158
+
159
+ return {
160
+ before() {
161
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/"))) return false;
162
+ },
163
+ ImportDeclaration(node) {
164
+ if (node.source.value === "effect") {
165
+ for (const specifier of node.specifiers) {
166
+ const local = localNameOf(specifier);
167
+ if (local === undefined) continue;
168
+ if (specifier.type === "ImportNamespaceSpecifier") effectNamespaceNames.add(local);
169
+ const imported = importedNameOf(specifier);
170
+ if (specifier.type === "ImportSpecifier" && imported === "Effect") {
171
+ effectNamespaceNames.add(local);
172
+ }
173
+ if (specifier.type === "ImportSpecifier" && imported === "pipe") pipeNames.add(local);
174
+ }
175
+ return;
176
+ }
177
+ if (node.source.value !== "effect/Effect") return;
178
+ for (const specifier of node.specifiers) {
179
+ const local = localNameOf(specifier);
180
+ if (local === undefined) continue;
181
+ if (
182
+ specifier.type === "ImportNamespaceSpecifier" ||
183
+ specifier.type === "ImportDefaultSpecifier"
184
+ ) {
185
+ effectNamespaceNames.add(local);
186
+ continue;
187
+ }
188
+ const imported = importedNameOf(specifier);
189
+ if (imported === "flatMap") flatMapNames.add(local);
190
+ else if (imported === "service") serviceNames.add(local);
191
+ }
192
+ },
193
+ CallExpression(node) {
194
+ if (!inStaticClassField(context.sourceCode, node)) return;
195
+ const args = node.arguments;
196
+ if (isEffectCall(node, "flatMap", flatMapNames) && args.length >= 2) {
197
+ const first = args[0];
198
+ if (first !== undefined && isServiceAcquisition(first) && isForwardingFlatMap(node)) {
199
+ context.report({ node, messageId: "staticForwarder" });
200
+ return;
201
+ }
202
+ }
203
+ const callee = node.callee;
204
+ let subject: ESTree.Node | undefined;
205
+ let operators: ReadonlyArray<ESTree.Argument>;
206
+ if (callee.type === "Identifier") {
207
+ if (!pipeNames.has(callee.name)) return;
208
+ subject = args[0];
209
+ operators = args.slice(1);
210
+ } else {
211
+ if (callee.type !== "MemberExpression" || memberName(callee) !== "pipe") {
212
+ return;
213
+ }
214
+ subject = callee.object;
215
+ operators = args;
216
+ }
217
+ if (
218
+ subject !== undefined &&
219
+ isServiceAcquisition(subject) &&
220
+ operators.some((operator) => isForwardingFlatMap(operator))
221
+ ) {
222
+ context.report({ node, messageId: "staticForwarder" });
223
+ }
224
+ },
225
+ };
226
+ },
227
+ });
@@ -0,0 +1,32 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+
3
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$|\/test\//u;
4
+
5
+ /** Raw `try`/`catch` detours failures around the typed error channel; route them through `Effect.try` instead. */
6
+ export const noTryCatchRule = defineRule({
7
+ meta: {
8
+ type: "problem",
9
+ docs: {
10
+ description:
11
+ "Disallow raw try/catch; move fallible work behind Effect.try (with a tagged failure reason) or let errors propagate through the typed channel. Unavoidable boundaries justify themselves with a SAFETY comment.",
12
+ },
13
+ messages: {
14
+ tryCatch:
15
+ "Raw `try`/`catch` detours this failure around the typed error channel. Use `Effect.try` (or `Effect.tryPromise`) failing a tagged reason, or let the error propagate. An integration boundary that must consume throwing APIs justifies itself with a `SAFETY:` comment.",
16
+ },
17
+ },
18
+ createOnce(context) {
19
+ return {
20
+ before() {
21
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/"))) return false;
22
+ },
23
+ TryStatement(node) {
24
+ const justified = context.sourceCode
25
+ .getCommentsBefore(node)
26
+ .some((comment) => /\bSAFETY\s*:/u.test(comment.value));
27
+ if (justified) return;
28
+ context.report({ node, messageId: "tryCatch" });
29
+ },
30
+ };
31
+ },
32
+ });
@@ -0,0 +1,211 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+
3
+ import type { ESTree, SourceCode } from "@oxlint/plugins";
4
+ import { ancestorsOf } from "../../shared/ancestors.ts";
5
+ import { readField } from "../../shared/structural.ts";
6
+
7
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$|\/test\//u;
8
+
9
+ const commentOwnerKinds = new Set([
10
+ "ExpressionStatement",
11
+ "ReturnStatement",
12
+ "ThrowStatement",
13
+ "VariableDeclaration",
14
+ ]);
15
+
16
+ /** Whether the nearest annotated function returns through the Effect/Either/Option channel.
17
+ *
18
+ * @param {SourceCode} sourceCode - The rule's source-code accessor.
19
+ * @param {ESTree.Node} node - The JSON.parse call expression.
20
+ * @returns {boolean} True when an enclosing function declares a channel return type.
21
+ */
22
+ function insideChannelReturningFunction(sourceCode: SourceCode, node: ESTree.Node): boolean {
23
+ const chain = ancestorsOf(sourceCode, node);
24
+ for (let index = chain.length - 1; index >= 0; index--) {
25
+ const current = chain[index]!;
26
+ if (current.type === "Program") break;
27
+ if (
28
+ current.type !== "FunctionDeclaration" &&
29
+ current.type !== "FunctionExpression" &&
30
+ current.type !== "ArrowFunctionExpression"
31
+ ) {
32
+ continue;
33
+ }
34
+ const returnType = current.returnType?.typeAnnotation;
35
+ if (returnType == null) continue;
36
+ const text = annotationText(returnType);
37
+ if (/\b(?:Effect|Either|Option)(?:\.|\b)/u.test(text)) return true;
38
+ }
39
+ return false;
40
+ }
41
+
42
+ /** Render an annotation to text so qualified names like Effect.Effect match.
43
+ *
44
+ * @param {ESTree.TSType} type - The type node to render.
45
+ * @returns {string} A space-joined textual sketch of the annotation.
46
+ */
47
+ function annotationText(type: ESTree.TSType): string {
48
+ switch (type.type) {
49
+ case "TSTypeReference": {
50
+ const name = type.typeName;
51
+ const head =
52
+ name.type === "Identifier"
53
+ ? name.name
54
+ : name.type === "TSQualifiedName"
55
+ ? name.right.name
56
+ : "";
57
+ const args = readField<{ params?: Array<ESTree.TSType> }>(type, "typeArguments");
58
+ const renderedArgs = args?.params?.map(annotationText).join(" ") ?? "";
59
+ return `${head} ${renderedArgs}`;
60
+ }
61
+ case "TSUnionType":
62
+ case "TSIntersectionType":
63
+ return type.types.map(annotationText).join(" ");
64
+ case "TSTupleType": {
65
+ const render = (element: ESTree.TSTupleElement): string => {
66
+ if ("elementType" in element) return render(element.elementType);
67
+ if (element.type === "TSOptionalType" || element.type === "TSRestType") {
68
+ return annotationText(element.typeAnnotation);
69
+ }
70
+ return annotationText(element);
71
+ };
72
+ return type.elementTypes.map(render).join(" ");
73
+ }
74
+ case "TSTypeOperator":
75
+ return annotationText(type.typeAnnotation);
76
+ case "TSArrayType":
77
+ return annotationText(type.elementType);
78
+ default:
79
+ return "";
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Whether a call targets Effect.try or Effect.trySync.
85
+ *
86
+ * @param {ESTree.Node} node - The candidate call expression.
87
+ * @returns {boolean} True when the call is an Effect.try family invocation.
88
+ */
89
+ function isEffectTryCall(node: ESTree.Node): boolean {
90
+ if (node.type !== "CallExpression") return false;
91
+ const callee = node.callee;
92
+ return (
93
+ callee.type === "MemberExpression" &&
94
+ !callee.computed &&
95
+ callee.object.type === "Identifier" &&
96
+ callee.object.name === "Effect" &&
97
+ callee.property.type === "Identifier" &&
98
+ (callee.property.name === "try" || callee.property.name === "trySync")
99
+ );
100
+ }
101
+
102
+ /**
103
+ * Guard recognition for a JSON.parse site.
104
+ *
105
+ * A thunk handed straight to Effect.try through an object literal
106
+ * ({ try: () => ..., catch: ... }) counts as guarded: climb past pure
107
+ * containers (Property, ObjectExpression, ArrayExpression) and resume the
108
+ * walk at the container exit, re-processing it.
109
+ *
110
+ * @param {SourceCode} sourceCode - The rule's source-code accessor.
111
+ * @param {ESTree.Node} node - The JSON.parse call expression.
112
+ * @returns {boolean} True when the parse site is guarded.
113
+ */
114
+ function isGuardedParse(sourceCode: SourceCode, node: ESTree.Node): boolean {
115
+ const chain = [...ancestorsOf(sourceCode, node)].reverse();
116
+ let index = 0;
117
+ while (index < chain.length) {
118
+ const current = chain[index]!;
119
+ if (current.type === "Program") return false;
120
+ if (current.type === "TryStatement") return true;
121
+ if (isEffectTryCall(current)) return true;
122
+ if (
123
+ current.type === "FunctionDeclaration" ||
124
+ current.type === "FunctionExpression" ||
125
+ current.type === "ArrowFunctionExpression"
126
+ ) {
127
+ let probeIndex = index + 1;
128
+ while (
129
+ probeIndex < chain.length &&
130
+ (chain[probeIndex]!.type === "Property" ||
131
+ chain[probeIndex]!.type === "ObjectExpression" ||
132
+ chain[probeIndex]!.type === "ArrayExpression")
133
+ ) {
134
+ probeIndex += 1;
135
+ }
136
+ if (probeIndex < chain.length && isEffectTryCall(chain[probeIndex]!)) {
137
+ index = probeIndex;
138
+ continue;
139
+ }
140
+ return false;
141
+ }
142
+ index += 1;
143
+ }
144
+ return false;
145
+ }
146
+
147
+ /**
148
+ * Whether a SAFETY comment covers this parse site or one of its statement owners.
149
+ *
150
+ * @param {SourceCode} sourceCode - The rule's source-code accessor.
151
+ * @param {ESTree.Node} node - The JSON.parse call expression.
152
+ * @returns {boolean} True when an applicable SAFETY justification exists.
153
+ */
154
+ function hasSafetyComment(sourceCode: SourceCode, node: ESTree.Node): boolean {
155
+ const chain: Array<ESTree.Node> = [node, ...[...ancestorsOf(sourceCode, node)].reverse()];
156
+ for (let index = 0; index < chain.length; index += 1) {
157
+ const current = chain[index]!;
158
+ if (
159
+ sourceCode
160
+ .getCommentsBefore(current)
161
+ .some((comment) => comment.end <= node.start && /\bSAFETY\s*:/u.test(comment.value))
162
+ ) {
163
+ return true;
164
+ }
165
+ if (commentOwnerKinds.has(current.type)) return false;
166
+ const parent = chain[index + 1];
167
+ if (parent === undefined || parent.type === "Program") return false;
168
+ }
169
+ return false;
170
+ }
171
+
172
+ /**
173
+ * JSON.parse throws a raw SyntaxError defect. Inside an Effect/Either/Option
174
+ * channel that bypasses the typed failure path unless explicitly guarded.
175
+ */
176
+ export const noUnguardedJsonParseRule = defineRule({
177
+ meta: {
178
+ type: "problem",
179
+ docs: {
180
+ description:
181
+ "Require JSON.parse inside Effect/Either/Option-returning functions to be channelled through Effect.try (or a try/catch), or justified with a SAFETY comment for provably-total parses.",
182
+ },
183
+ messages: {
184
+ unguardedParse:
185
+ "`JSON.parse` here throws a raw SyntaxError defect past the typed error channel. Channel it with `Effect.try({ try: ..., catch: ... })` failing a tagged reason (e.g. MalformedRenderError), or justify totality with a `SAFETY:` comment.",
186
+ },
187
+ },
188
+ createOnce(context) {
189
+ return {
190
+ before() {
191
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/"))) return false;
192
+ },
193
+ CallExpression(node) {
194
+ const callee = node.callee;
195
+ if (
196
+ callee.type !== "MemberExpression" ||
197
+ callee.computed ||
198
+ callee.object.type !== "Identifier" ||
199
+ callee.object.name !== "JSON" ||
200
+ callee.property.type !== "Identifier" ||
201
+ callee.property.name !== "parse"
202
+ )
203
+ return;
204
+ if (!insideChannelReturningFunction(context.sourceCode, node)) return;
205
+ if (isGuardedParse(context.sourceCode, node)) return;
206
+ if (hasSafetyComment(context.sourceCode, node)) return;
207
+ context.report({ node, messageId: "unguardedParse" });
208
+ },
209
+ };
210
+ },
211
+ });
@@ -0,0 +1,81 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+
3
+ import type { ESTree } from "@oxlint/plugins";
4
+
5
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$|\/test\//u;
6
+
7
+ /** The exported name declared by this statement, if any.
8
+ *
9
+ * @param {ESTree.Node} node - The export or declaration statement.
10
+ * @returns {string | null} The declared binding name, or null when anonymous.
11
+ */
12
+ function exportedName(node: ESTree.Node): string | null {
13
+ if (node.type === "ExportNamedDeclaration") {
14
+ const declaration = node.declaration;
15
+ if (declaration === null || declaration === undefined) return null;
16
+ if (declaration.type === "FunctionDeclaration" && declaration.id !== null) {
17
+ return declaration.id.name;
18
+ }
19
+ if (declaration.type === "VariableDeclaration") {
20
+ for (const declarator of declaration.declarations) {
21
+ if (declarator.id.type === "Identifier") return declarator.id.name;
22
+ }
23
+ }
24
+ }
25
+ return null;
26
+ }
27
+
28
+ /**
29
+ * Every exported `*Option` guarded core must have a converted public twin in the
30
+ * same module, so Option-shaped internals cannot silently become the public API.
31
+ */
32
+ export const optionCoreNeedsEffectPublicRule = defineRule({
33
+ meta: {
34
+ type: "problem",
35
+ docs: {
36
+ description:
37
+ "Require every exported *Option guarded core to be paired with a converted public API that owns the typed error channel.",
38
+ },
39
+ messages: {
40
+ missingTwin:
41
+ "`{{name}}` collapses failures to `Option.none()` with no converted public twin. Export `{{base}}` returning `Effect.Effect<T, MoneyError>` (or mark the core `@deprecated` if retired), so callers can match Overflow vs InvalidInput vs ZeroDivisor.",
42
+ },
43
+ },
44
+ createOnce(context) {
45
+ const cores: Array<{ node: ESTree.Node; name: string; base: string }> = [];
46
+ const exported = new Set<string>();
47
+ return {
48
+ before() {
49
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/"))) return false;
50
+ cores.length = 0;
51
+ exported.clear();
52
+ },
53
+ "ExportNamedDeclaration > VariableDeclaration > VariableDeclarator, ExportNamedDeclaration > FunctionDeclaration":
54
+ (node: ESTree.Node) => {
55
+ const declaratorId = node.type === "VariableDeclarator" ? node.id : null;
56
+ const name =
57
+ node.type === "FunctionDeclaration"
58
+ ? (node.id?.name ?? null)
59
+ : declaratorId?.type === "Identifier"
60
+ ? declaratorId.name
61
+ : null;
62
+ if (name === null) return;
63
+ exported.add(name);
64
+ if (name.endsWith("Option")) {
65
+ cores.push({ node, name, base: name.slice(0, -"Option".length) });
66
+ }
67
+ },
68
+ "Program:exit"() {
69
+ for (const core of cores) {
70
+ if (!exported.has(core.base)) {
71
+ context.report({
72
+ node: core.node,
73
+ messageId: "missingTwin",
74
+ data: { name: core.name, base: core.base },
75
+ });
76
+ }
77
+ }
78
+ },
79
+ };
80
+ },
81
+ });
@@ -0,0 +1,118 @@
1
+ import { defineRule } from "@oxlint/plugins";
2
+
3
+ import type { ESTree } from "@oxlint/plugins";
4
+ import { readField } from "../../shared/structural.ts";
5
+ import { ancestorsOf } from "../../shared/ancestors.ts";
6
+
7
+ const TEST_FILE = /.(?:test|spec).[cm]?[jt]sx?$|\/test\//u;
8
+
9
+ /** Unwrap a tuple element to the type node it contributes to the annotation walk.
10
+ *
11
+ * @param {ESTree.TSTupleElement} element - Tuple element node.
12
+ * @returns {ESTree.TSType} The underlying type node.
13
+ */
14
+ function tupleElementType(element: ESTree.TSTupleElement): ESTree.TSType {
15
+ if (element.type === "TSOptionalType" || element.type === "TSRestType") {
16
+ return element.typeAnnotation;
17
+ }
18
+ if ("elementType" in element) return tupleElementType(element.elementType);
19
+ return element;
20
+ }
21
+
22
+ /** Whether the annotation references the Effect or Either channel (defect-capable).
23
+ *
24
+ * @param {ESTree.Node} node - A function-like node whose return annotation is inspected.
25
+ * @returns {boolean} True when the return annotation mentions Effect or Either.
26
+ */
27
+ function returnsEffectOrFailChannel(node: ESTree.Node): boolean {
28
+ if (
29
+ node.type !== "FunctionDeclaration" &&
30
+ node.type !== "FunctionExpression" &&
31
+ node.type !== "ArrowFunctionExpression"
32
+ ) {
33
+ return false;
34
+ }
35
+ const annotation = node.returnType?.typeAnnotation;
36
+ if (annotation === undefined) return false;
37
+ const seen: Array<ESTree.TSType> = [annotation];
38
+ while (seen.length > 0) {
39
+ const type = seen.pop();
40
+ if (type === undefined) continue;
41
+ switch (type.type) {
42
+ case "TSTypeReference": {
43
+ const name = type.typeName;
44
+ const head =
45
+ name.type === "Identifier"
46
+ ? name.name
47
+ : name.type === "TSQualifiedName"
48
+ ? name.left.type === "Identifier"
49
+ ? name.left.name
50
+ : null
51
+ : null;
52
+ if (head === "Effect" || head === "Either") {
53
+ return true;
54
+ }
55
+ const args = readField<{ params?: Array<ESTree.TSType> }>(type, "typeArguments");
56
+ if (args?.params !== undefined) seen.push(...args.params);
57
+ break;
58
+ }
59
+ case "TSUnionType":
60
+ case "TSIntersectionType":
61
+ seen.push(...type.types);
62
+ break;
63
+ case "TSTupleType":
64
+ for (const element of type.elementTypes) {
65
+ seen.push(tupleElementType(element));
66
+ }
67
+ break;
68
+ case "TSTypeOperator":
69
+ seen.push(type.typeAnnotation);
70
+ break;
71
+ case "TSArrayType":
72
+ seen.push(type.elementType);
73
+ break;
74
+ default:
75
+ break;
76
+ }
77
+ }
78
+ return false;
79
+ }
80
+
81
+ /**
82
+ * Precondition violations are defects by doctrine: thrown directly they escape
83
+ * the Cause, invisible to telemetry and supervisors.
84
+ */
85
+ export const preferDieForPreconditionDefectsRule = defineRule({
86
+ meta: {
87
+ type: "problem",
88
+ docs: {
89
+ description:
90
+ "In Effect/Either-returning functions, raise precondition defects with Effect.die instead of a bare throw so they travel inside the Cause.",
91
+ },
92
+ messages: {
93
+ bareThrow:
94
+ "This bare throw escapes the Effect `Cause`. Raise the tagged defect with `Effect.die(new ...)` (or reclassify the case as a typed failure on the error channel) so supervisors and telemetry observe it.",
95
+ },
96
+ },
97
+ createOnce(context) {
98
+ const check = (node: ESTree.ThrowStatement): void => {
99
+ const ancestors = ancestorsOf(context.sourceCode, node);
100
+ for (let index = ancestors.length - 1; index >= 0; index--) {
101
+ const current = ancestors[index]!;
102
+ if (current.type === "Program") break;
103
+ if (
104
+ current.type === "FunctionDeclaration" ||
105
+ current.type === "FunctionExpression" ||
106
+ current.type === "ArrowFunctionExpression"
107
+ ) {
108
+ if (returnsEffectOrFailChannel(current)) context.report({ node, messageId: "bareThrow" });
109
+ return;
110
+ }
111
+ }
112
+ };
113
+ return { before() {
114
+ if (TEST_FILE.test(context.filename.replaceAll("\\", "/"))) return false;
115
+ },
116
+ ThrowStatement: check };
117
+ },
118
+ });