@milkenjoyer/toolchain 0.0.0-stage → 0.6.5
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.
- package/README.md +36 -2
- package/dist/array-method-C_XYdjLZ.mjs +178 -0
- package/dist/compatible.d.mts +91 -0
- package/dist/compatible.mjs +160 -0
- package/dist/effect-plugin-DARbVmA3.mjs +3493 -0
- package/dist/effect-plugin.d.mts +3967 -0
- package/dist/effect-plugin.mjs +1 -0
- package/dist/effect-tsgo.d.mts +10 -0
- package/dist/effect-tsgo.mjs +16 -0
- package/dist/exceptions.d.mts +6 -0
- package/dist/exceptions.mjs +16 -0
- package/dist/fmt.d.mts +5 -0
- package/dist/fmt.mjs +8 -0
- package/dist/foldkit.d.mts +3 -0
- package/dist/foldkit.mjs +17 -0
- package/dist/guard.d.mts +32 -0
- package/dist/guard.mjs +131 -0
- package/dist/hooks.d.mts +16 -0
- package/dist/hooks.mjs +137 -0
- package/dist/index.d.mts +1 -0
- package/dist/index.mjs +3 -0
- package/dist/knip.d.mts +7 -0
- package/dist/knip.mjs +15 -0
- package/dist/lint.d.mts +9 -0
- package/dist/lint.mjs +113 -0
- package/dist/plugin-CBUJ7Tgd.mjs +927 -0
- package/dist/plugin.d.mts +19 -0
- package/dist/plugin.mjs +1 -0
- package/dist/rikalabs-hPKWFZ1P.mjs +362 -0
- package/dist/rikalabs.d.mts +80 -0
- package/dist/rikalabs.mjs +1 -0
- package/dist/rules.d.mts +246 -0
- package/dist/rules.mjs +234 -0
- package/dist/versions.d.mts +46 -0
- package/dist/versions.mjs +148 -0
- package/licenses/anti-slop.txt +21 -0
- package/licenses/oxlint-plugin-effect.txt +21 -0
- package/node-version +1 -0
- package/package.json +114 -4
- package/renovate.json +78 -0
- package/tsconfig.base.json +34 -0
- package/vscode/extensions.json +3 -0
- package/vscode/settings.json +6 -0
|
@@ -0,0 +1,927 @@
|
|
|
1
|
+
import { a as effectReferenceName, c as memberPropertyName, i as collectEffectImports, l as propertyName, n as isKnownArrayExpression, o as isMatchPatternObject, r as unwrapExpression, s as isStringLiteral, t as arrayMethodTarget, u as resolveBinding } from "./array-method-C_XYdjLZ.mjs";
|
|
2
|
+
import * as Arr from "effect/Array";
|
|
3
|
+
import { dual } from "effect/Function";
|
|
4
|
+
import * as HashSet from "effect/HashSet";
|
|
5
|
+
import * as Option from "effect/Option";
|
|
6
|
+
import * as R from "effect/Record";
|
|
7
|
+
import * as Schema from "effect/Schema";
|
|
8
|
+
import * as Str from "effect/String";
|
|
9
|
+
import { Comment, Diagnostic, Plugin, Rule, RuleContext } from "effect-oxlint";
|
|
10
|
+
import * as Effect from "effect/Effect";
|
|
11
|
+
import * as HashMap from "effect/HashMap";
|
|
12
|
+
import * as Cause from "effect/Cause";
|
|
13
|
+
// src/rules/no-ambient-crypto.ts
|
|
14
|
+
const CRYPTO_METHODS = HashSet.fromIterable([
|
|
15
|
+
"randomUUID",
|
|
16
|
+
"getRandomValues",
|
|
17
|
+
"randomBytes",
|
|
18
|
+
"randomInt"
|
|
19
|
+
]);
|
|
20
|
+
const GLOBAL_OBJECTS = HashSet.fromIterable([
|
|
21
|
+
"globalThis",
|
|
22
|
+
"self",
|
|
23
|
+
"window"
|
|
24
|
+
]);
|
|
25
|
+
const isCryptoModule = (source) => source === "node:crypto" || source === "crypto";
|
|
26
|
+
const isAmbientMethod = (source, name) => source === "math" ? name === "random" : HashSet.has(CRYPTO_METHODS, name);
|
|
27
|
+
const sourceName = (name) => {
|
|
28
|
+
if (name === "Math") return Option.some("math");
|
|
29
|
+
return name === "crypto" ? Option.some("crypto") : Option.none();
|
|
30
|
+
};
|
|
31
|
+
const isGlobal = (sourceCode, node) => Option.match(resolveBinding(sourceCode, node), {
|
|
32
|
+
onNone: () => true,
|
|
33
|
+
onSome: (variable) => Arr.isReadonlyArrayEmpty(variable.defs)
|
|
34
|
+
});
|
|
35
|
+
const isGlobalObject = (sourceCode, node) => node.type === "Identifier" && HashSet.has(GLOBAL_OBJECTS, node.name) && isGlobal(sourceCode, node);
|
|
36
|
+
const ambientSource = (sourceCode, node, visited = []) => {
|
|
37
|
+
if (visited.includes(node)) return Option.none();
|
|
38
|
+
if (node.type === "Identifier") {
|
|
39
|
+
if (isGlobal(sourceCode, node)) return sourceName(node.name);
|
|
40
|
+
return Option.flatMap(resolveBinding(sourceCode, node), (variable) => Arr.head(Arr.flatMap(variable.defs, (definition) => {
|
|
41
|
+
if (definition.type === "ImportBinding" && definition.parent?.type === "ImportDeclaration" && definition.parent.importKind !== "type" && isCryptoModule(definition.parent.source.value) && (definition.node.type === "ImportDefaultSpecifier" || definition.node.type === "ImportNamespaceSpecifier")) return ["crypto"];
|
|
42
|
+
return definition.node.type === "VariableDeclarator" && definition.node.id.type === "Identifier" && definition.node.init !== null && Option.contains(ambientSource(sourceCode, definition.node.init, [...visited, node]), "math") ? ["math"] : [];
|
|
43
|
+
})));
|
|
44
|
+
}
|
|
45
|
+
if (node.type === "MemberExpression" && isGlobalObject(sourceCode, node.object)) return Option.flatMap(memberPropertyName(node), sourceName);
|
|
46
|
+
return Option.none();
|
|
47
|
+
};
|
|
48
|
+
const ambientImports = (node) => node.type === "ImportDeclaration" && node.importKind !== "type" && isCryptoModule(node.source.value) ? Arr.filter(node.specifiers, (specifier) => specifier.type === "ImportSpecifier" && specifier.importKind !== "type" && HashSet.has(CRYPTO_METHODS, specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value)) : [];
|
|
49
|
+
const objectPattern = (node) => {
|
|
50
|
+
if (node.type === "AssignmentPattern") return objectPattern(node.left);
|
|
51
|
+
return node.type === "ObjectPattern" ? Option.some(node) : Option.none();
|
|
52
|
+
};
|
|
53
|
+
const propertiesNamed = (pattern, names) => Option.match(objectPattern(pattern), {
|
|
54
|
+
onNone: () => [],
|
|
55
|
+
onSome: (object) => Arr.flatMap(object.properties, (property) => property.type === "Property" && Option.exists(propertyName(property), names) ? [property] : [])
|
|
56
|
+
});
|
|
57
|
+
const ambientMethods = (pattern, source) => propertiesNamed(pattern, (name) => isAmbientMethod(source, name));
|
|
58
|
+
const destructuredAmbient = (sourceCode, pattern, source) => {
|
|
59
|
+
const recognized = ambientSource(sourceCode, source);
|
|
60
|
+
if (Option.isSome(recognized)) return ambientMethods(pattern, recognized.value);
|
|
61
|
+
return isGlobalObject(sourceCode, source) ? Arr.flatMap(propertiesNamed(pattern, (name) => name === "crypto" || name === "Math"), (property) => ambientMethods(property.value, Option.contains(propertyName(property), "Math") ? "math" : "crypto")) : [];
|
|
62
|
+
};
|
|
63
|
+
const noAmbientCryptoRule = Rule.define({
|
|
64
|
+
*create() {
|
|
65
|
+
const context = yield* RuleContext;
|
|
66
|
+
const reportEach = (nodes) => Effect.forEach(nodes, (node) => context.report(Diagnostic.fromId({
|
|
67
|
+
messageId: "ambientCrypto",
|
|
68
|
+
node
|
|
69
|
+
})), {
|
|
70
|
+
concurrency: 1,
|
|
71
|
+
discard: true
|
|
72
|
+
});
|
|
73
|
+
return {
|
|
74
|
+
MemberExpression: (node) => {
|
|
75
|
+
if (node.type !== "MemberExpression" || !Option.exists(ambientSource(context.sourceCode, node.object), (source) => Option.exists(memberPropertyName(node), (name) => isAmbientMethod(source, name)))) return Effect.void;
|
|
76
|
+
return reportEach([node]);
|
|
77
|
+
},
|
|
78
|
+
ImportDeclaration: (node) => reportEach(ambientImports(node)),
|
|
79
|
+
VariableDeclarator: (node) => node.type === "VariableDeclarator" && node.init !== null ? reportEach(destructuredAmbient(context.sourceCode, node.id, node.init)) : Effect.void,
|
|
80
|
+
AssignmentExpression: (node) => node.type === "AssignmentExpression" ? reportEach(destructuredAmbient(context.sourceCode, node.left, node.right)) : Effect.void
|
|
81
|
+
};
|
|
82
|
+
},
|
|
83
|
+
meta: Rule.meta({
|
|
84
|
+
description: "Use Effect Random for Math.random and SecureRandom for ambient or node crypto randomness",
|
|
85
|
+
messages: { ambientCrypto: "Use Effect Random instead of Math.random. For crypto.randomUUID, crypto.getRandomValues, crypto.randomBytes or crypto.randomInt (including node:crypto imports), use `yield* SecureRandom.SecureRandom` from effect/crypto/SecureRandom (uuidV4, uuidV7, randomBytes), and give tests a deterministic SecureRandom layer. crypto.subtle stays allowed." },
|
|
86
|
+
type: "problem"
|
|
87
|
+
}),
|
|
88
|
+
name: "no-ambient-crypto"
|
|
89
|
+
});
|
|
90
|
+
// src/rules/no-array-filter-map.ts
|
|
91
|
+
const noArrayFilterMapRule = Rule.define({
|
|
92
|
+
*create() {
|
|
93
|
+
const context = yield* RuleContext;
|
|
94
|
+
return { CallExpression: (node) => {
|
|
95
|
+
if (node.type !== "CallExpression") return Effect.void;
|
|
96
|
+
const outer = arrayMethodTarget(node.callee);
|
|
97
|
+
if (Option.isNone(outer) || outer.value.name !== "map" && outer.value.name !== "filter") return Effect.void;
|
|
98
|
+
const innerCall = unwrapExpression(outer.value.object);
|
|
99
|
+
if (innerCall.type !== "CallExpression") return Effect.void;
|
|
100
|
+
const inner = arrayMethodTarget(innerCall.callee);
|
|
101
|
+
if (Option.isNone(inner) || inner.value.name !== (outer.value.name === "map" ? "filter" : "map") || !isKnownArrayExpression(context.sourceCode, inner.value.object)) return Effect.void;
|
|
102
|
+
return context.report(Diagnostic.fromId({
|
|
103
|
+
data: {
|
|
104
|
+
first: inner.value.name,
|
|
105
|
+
second: outer.value.name
|
|
106
|
+
},
|
|
107
|
+
messageId: "arrayFilterMap",
|
|
108
|
+
node
|
|
109
|
+
}));
|
|
110
|
+
} };
|
|
111
|
+
},
|
|
112
|
+
meta: Rule.meta({
|
|
113
|
+
description: "A single transformation or lazy iterator helpers instead of adjacent array `filter`/`map` passes",
|
|
114
|
+
messages: { arrayFilterMap: "Avoid consecutive array `{{first}}` and `{{second}}` passes. Prefer `.values().{{first}}(...).{{second}}(...).toArray()` where iterator helpers are supported, or a single `flatMap`/mutating reducer. Preserve callback ordering, indexes, and filtering semantics." },
|
|
115
|
+
type: "suggestion"
|
|
116
|
+
}),
|
|
117
|
+
name: "no-array-filter-map"
|
|
118
|
+
});
|
|
119
|
+
// src/rules/no-comments.ts
|
|
120
|
+
const noCommentsRule = Rule.define({
|
|
121
|
+
*create() {
|
|
122
|
+
const context = yield* RuleContext;
|
|
123
|
+
return { Program: () => Effect.forEach(Arr.filter(context.sourceCode.getAllComments(), (comment) => !Comment.isShebang(comment) && !/^\s*@vite-ignore\s*$/u.test(Comment.text(comment))), (comment) => context.report(Diagnostic.fromId({
|
|
124
|
+
messageId: "comment",
|
|
125
|
+
node: comment
|
|
126
|
+
})), {
|
|
127
|
+
concurrency: 1,
|
|
128
|
+
discard: true
|
|
129
|
+
}) };
|
|
130
|
+
},
|
|
131
|
+
meta: Rule.meta({
|
|
132
|
+
description: "No comments except shebangs and exact @vite-ignore directives: meaning lives in names, types and test names",
|
|
133
|
+
messages: { comment: "Delete this comment. Put its meaning in a name, a type or a test name. Only shebangs and exact @vite-ignore directives are allowed." },
|
|
134
|
+
type: "problem"
|
|
135
|
+
}),
|
|
136
|
+
name: "no-comments"
|
|
137
|
+
});
|
|
138
|
+
// src/shared/file-role.ts
|
|
139
|
+
const TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/u;
|
|
140
|
+
const isRoleFile = dual(3, (role, filename, cwd) => {
|
|
141
|
+
if (TEST_FILE.test(filename)) return false;
|
|
142
|
+
const relative = Str.startsWith(`${cwd}/`)(filename) ? Str.slice(cwd.length + 1)(filename) : filename;
|
|
143
|
+
const parts = Str.split(relative, /[\\/]/u);
|
|
144
|
+
const stem = Str.replace(/\.[^.]+$/u, "")(parts.at(-1) ?? "");
|
|
145
|
+
return Arr.some(parts.slice(0, -1), (part) => part === role || part === `${role}s`) || stem === role || Str.endsWith(`-${role}`)(stem) || Str.endsWith(`.${role}`)(stem);
|
|
146
|
+
});
|
|
147
|
+
// src/shared/global-use.ts
|
|
148
|
+
const CONTAINERS = HashSet.make("globalThis", "self");
|
|
149
|
+
const withoutContainers = (path) => Arr.match(path, {
|
|
150
|
+
onEmpty: () => path,
|
|
151
|
+
onNonEmpty: ([first, ...rest]) => Arr.isReadonlyArrayNonEmpty(rest) && HashSet.has(CONTAINERS, first) ? withoutContainers(rest) : path
|
|
152
|
+
});
|
|
153
|
+
const settle = (node, path) => {
|
|
154
|
+
const { parent } = node;
|
|
155
|
+
const whole = {
|
|
156
|
+
path: withoutContainers(path),
|
|
157
|
+
node,
|
|
158
|
+
invocation: "none",
|
|
159
|
+
argumentCount: 0
|
|
160
|
+
};
|
|
161
|
+
if (parent?.type === "VariableDeclarator" && parent.init === node && parent.id.type === "ObjectPattern") {
|
|
162
|
+
const { properties } = parent.id;
|
|
163
|
+
const named = Arr.flatMap(properties, (property) => property.type === "Property" ? Arr.fromOption(Option.map(propertyName(property), (name) => ({
|
|
164
|
+
...whole,
|
|
165
|
+
path: withoutContainers([...path, name]),
|
|
166
|
+
node: property
|
|
167
|
+
}))) : []);
|
|
168
|
+
return named.length === properties.length ? named : [...named, whole];
|
|
169
|
+
}
|
|
170
|
+
if ((parent?.type === "CallExpression" || parent?.type === "NewExpression") && parent.callee === node) return [{
|
|
171
|
+
...whole,
|
|
172
|
+
node: parent,
|
|
173
|
+
invocation: parent.type === "CallExpression" ? "call" : "new",
|
|
174
|
+
argumentCount: parent.arguments.length
|
|
175
|
+
}];
|
|
176
|
+
return [whole];
|
|
177
|
+
};
|
|
178
|
+
const climb = (node, path) => {
|
|
179
|
+
const { parent } = node;
|
|
180
|
+
if (parent?.type !== "MemberExpression" || parent.object !== node) return settle(node, path);
|
|
181
|
+
return Option.match(memberPropertyName(parent), {
|
|
182
|
+
onNone: () => settle(node, path),
|
|
183
|
+
onSome: (name) => climb(parent, [...path, name])
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
const isTypeQuery = (node) => {
|
|
187
|
+
const { parent } = node;
|
|
188
|
+
if (parent === null) return false;
|
|
189
|
+
return parent.type === "TSTypeQuery" || parent.type === "TSQualifiedName" && isTypeQuery(parent);
|
|
190
|
+
};
|
|
191
|
+
const globalUses = dual(2, (sourceCode, node) => node.type === "Identifier" && !isTypeQuery(node) && Arr.some(sourceCode.getScope(node).references, (reference) => reference.identifier === node && (reference.resolved === null || Arr.isArrayEmpty(reference.resolved.defs))) ? climb(node, [node.name]) : []);
|
|
192
|
+
// src/rules/no-impure-update-file.ts
|
|
193
|
+
const IMPURE_MEMBERS = HashSet.make("Math.random", "Date.now", "performance.now");
|
|
194
|
+
const DOM_ROOTS = HashSet.make("document", "window");
|
|
195
|
+
const impurity = (use) => {
|
|
196
|
+
const [root = "", member] = use.path;
|
|
197
|
+
if (HashSet.has(DOM_ROOTS, root)) return Option.some(root);
|
|
198
|
+
if (root === "console") return Option.some(member === void 0 ? root : `${root}.${member}`);
|
|
199
|
+
if (HashSet.has(IMPURE_MEMBERS, `${root}.${member ?? ""}`)) return Option.some(`${root}.${member ?? ""}()`);
|
|
200
|
+
if (root !== "Date" || member !== void 0) return Option.none();
|
|
201
|
+
if (use.invocation === "call") return Option.some("Date()");
|
|
202
|
+
return use.invocation === "new" && use.argumentCount === 0 ? Option.some("new Date()") : Option.none();
|
|
203
|
+
};
|
|
204
|
+
const noImpureUpdateFileRule = Rule.define({
|
|
205
|
+
*create() {
|
|
206
|
+
const context = yield* RuleContext;
|
|
207
|
+
if (!isRoleFile("update", context.filename, context.cwd)) return {};
|
|
208
|
+
return { Identifier: (node) => Effect.forEach(globalUses(context.sourceCode, node), (use) => Option.match(impurity(use), {
|
|
209
|
+
onNone: () => Effect.void,
|
|
210
|
+
onSome: (name) => context.report(Diagnostic.fromId({
|
|
211
|
+
data: { name },
|
|
212
|
+
messageId: "impureUpdate",
|
|
213
|
+
node: use.node
|
|
214
|
+
}))
|
|
215
|
+
}), {
|
|
216
|
+
concurrency: 1,
|
|
217
|
+
discard: true
|
|
218
|
+
}) };
|
|
219
|
+
},
|
|
220
|
+
meta: Rule.meta({
|
|
221
|
+
description: "Files under an update path stay pure: no clock, randomness, console, document or window",
|
|
222
|
+
messages: { impureUpdate: "Remove `{{name}}` from this update file. update returns { model, commands } and does nothing else: time, randomness, logging and the DOM come from a Command defined with Command.define, whose result comes back as a Message." },
|
|
223
|
+
type: "problem"
|
|
224
|
+
}),
|
|
225
|
+
name: "no-impure-update-file"
|
|
226
|
+
});
|
|
227
|
+
// src/rules/no-impure-view-file.ts
|
|
228
|
+
const LISTENER = "addEventListener";
|
|
229
|
+
const BANNED_ROOTS = HashSet.make("document", "window", "fetch", "setTimeout", "setInterval", "setImmediate", "requestAnimationFrame", "requestIdleCallback", LISTENER);
|
|
230
|
+
const bannedName = (use) => Option.filter(Arr.head(use.path), (root) => HashSet.has(BANNED_ROOTS, root));
|
|
231
|
+
const rootIdentifier = (node) => {
|
|
232
|
+
const current = unwrapExpression(node);
|
|
233
|
+
if (current.type === "MemberExpression") return rootIdentifier(current.object);
|
|
234
|
+
return current.type === "CallExpression" ? rootIdentifier(current.callee) : current;
|
|
235
|
+
};
|
|
236
|
+
const noImpureViewFileRule = Rule.define({
|
|
237
|
+
*create() {
|
|
238
|
+
const context = yield* RuleContext;
|
|
239
|
+
if (!isRoleFile("view", context.filename, context.cwd)) return {};
|
|
240
|
+
const report = (name, node) => context.report(Diagnostic.fromId({
|
|
241
|
+
data: { name },
|
|
242
|
+
messageId: "impureView",
|
|
243
|
+
node
|
|
244
|
+
}));
|
|
245
|
+
return {
|
|
246
|
+
Identifier: (node) => Effect.forEach(globalUses(context.sourceCode, node), (use) => Option.match(bannedName(use), {
|
|
247
|
+
onNone: () => Effect.void,
|
|
248
|
+
onSome: (name) => report(name, use.node)
|
|
249
|
+
}), {
|
|
250
|
+
concurrency: 1,
|
|
251
|
+
discard: true
|
|
252
|
+
}),
|
|
253
|
+
MemberExpression: (node) => {
|
|
254
|
+
if (node.type !== "MemberExpression" || !Option.contains(memberPropertyName(node), LISTENER)) return Effect.void;
|
|
255
|
+
return Arr.some(globalUses(context.sourceCode, rootIdentifier(node.object)), (use) => Option.isSome(bannedName(use))) ? Effect.void : report(LISTENER, node);
|
|
256
|
+
}
|
|
257
|
+
};
|
|
258
|
+
},
|
|
259
|
+
meta: Rule.meta({
|
|
260
|
+
description: "View files only build Html and Messages: no fetch, timers, addEventListener, document or window",
|
|
261
|
+
messages: { impureView: "Remove `{{name}}` from this view file. view returns Html built from the Model, and its event attributes build Messages; run requests, timers, listeners and DOM access in a Command, a Subscription or a Mount." },
|
|
262
|
+
type: "problem"
|
|
263
|
+
}),
|
|
264
|
+
name: "no-impure-view-file"
|
|
265
|
+
});
|
|
266
|
+
// src/rules/no-inline-exported-object-types.ts
|
|
267
|
+
const MIN_REPORTED_MEMBERS = 4;
|
|
268
|
+
const enclosingExport = (current) => {
|
|
269
|
+
if (Option.isNone(current) || current.value.type === "Program") return Option.none();
|
|
270
|
+
return current.value.type === "ExportNamedDeclaration" ? Option.some(current.value) : enclosingExport(Option.fromNullishOr(current.value.parent));
|
|
271
|
+
};
|
|
272
|
+
const noInlineExportedObjectTypesRule = Rule.define({
|
|
273
|
+
*create() {
|
|
274
|
+
const context = yield* RuleContext;
|
|
275
|
+
return { TSTypeLiteral: (node) => {
|
|
276
|
+
if (node.type !== "TSTypeLiteral" || node.members.length < MIN_REPORTED_MEMBERS) return Effect.void;
|
|
277
|
+
const exported = enclosingExport(Option.fromNullishOr(node.parent));
|
|
278
|
+
if (Option.isNone(exported) || node.parent.type === "TSTypeAliasDeclaration" && node.parent.typeAnnotation === node && node.parent.parent === exported.value) return Effect.void;
|
|
279
|
+
return context.report(Diagnostic.fromId({
|
|
280
|
+
data: { count: String(node.members.length) },
|
|
281
|
+
messageId: "inlineObjectType",
|
|
282
|
+
node: exported.value
|
|
283
|
+
}));
|
|
284
|
+
} };
|
|
285
|
+
},
|
|
286
|
+
meta: Rule.meta({
|
|
287
|
+
description: "Exported declarations use named types for object literals with four or more members; exported object type aliases own their bodies",
|
|
288
|
+
messages: { inlineObjectType: "Inline object type with {{count}} properties is too large for an exported API. Extract to a named type or interface." },
|
|
289
|
+
type: "problem"
|
|
290
|
+
}),
|
|
291
|
+
name: "no-inline-exported-object-types"
|
|
292
|
+
});
|
|
293
|
+
// src/shared/member-path.ts
|
|
294
|
+
const memberPath = (node) => {
|
|
295
|
+
const current = unwrapExpression(node);
|
|
296
|
+
if (current.type === "Identifier") return Option.some({
|
|
297
|
+
root: current,
|
|
298
|
+
members: []
|
|
299
|
+
});
|
|
300
|
+
if (current.type !== "MemberExpression") return Option.none();
|
|
301
|
+
return Option.flatMap(memberPath(current.object), (path) => Option.map(memberPropertyName(current), (name) => ({
|
|
302
|
+
root: path.root,
|
|
303
|
+
members: [...path.members, name]
|
|
304
|
+
})));
|
|
305
|
+
};
|
|
306
|
+
const lastName = (node) => Option.map(memberPath(node), (path) => Option.getOrElse(Arr.last(path.members), () => path.root.name));
|
|
307
|
+
const importedPath = dual(2, (sourceCode, node) => Option.gen(function* () {
|
|
308
|
+
const path = yield* memberPath(node);
|
|
309
|
+
const variable = yield* resolveBinding(sourceCode, path.root);
|
|
310
|
+
const definition = yield* Arr.findFirst(variable.defs, (candidate) => candidate.type === "ImportBinding");
|
|
311
|
+
const declaration = definition.parent;
|
|
312
|
+
const specifier = definition.node;
|
|
313
|
+
if (declaration?.type !== "ImportDeclaration") return yield* Option.none();
|
|
314
|
+
if (specifier.type === "ImportNamespaceSpecifier") return {
|
|
315
|
+
source: declaration.source.value,
|
|
316
|
+
members: path.members
|
|
317
|
+
};
|
|
318
|
+
if (specifier.type !== "ImportSpecifier") return yield* Option.none();
|
|
319
|
+
const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
|
|
320
|
+
return {
|
|
321
|
+
source: declaration.source.value,
|
|
322
|
+
members: [imported, ...path.members]
|
|
323
|
+
};
|
|
324
|
+
}));
|
|
325
|
+
// src/rules/no-keyed-row-index.ts
|
|
326
|
+
const INDEX_POSITION = HashMap.make(["filterMap", 1], ["flatMap", 1], ["from", 1], ["makeBy", 0], ["map", 1]);
|
|
327
|
+
const KEYED_MODULES = HashSet.make("effect/HashMap", "effect/Record");
|
|
328
|
+
const KEYED_NAMESPACES = HashSet.make("HashMap", "Record");
|
|
329
|
+
const enclosingRow = (sourceCode, node) => {
|
|
330
|
+
const fn = node.parent;
|
|
331
|
+
if (fn === null) return Option.none();
|
|
332
|
+
const call = fn.parent;
|
|
333
|
+
const row = (fn.type === "ArrowFunctionExpression" || fn.type === "FunctionExpression") && call?.type === "CallExpression" && call.arguments.includes(fn) ? Option.flatMap(lastName(call.callee), (iterator) => Option.map(HashMap.get(INDEX_POSITION, iterator), (position) => ({
|
|
334
|
+
parameter: Option.exists(importedPath(sourceCode, call.callee), ({ source, members }) => HashSet.has(KEYED_MODULES, source) || source === "effect" && Option.exists(Arr.head(members), (name) => HashSet.has(KEYED_NAMESPACES, name))) ? Option.none() : Option.fromUndefinedOr(fn.params.at(position)),
|
|
335
|
+
iterator
|
|
336
|
+
}))) : Option.none();
|
|
337
|
+
return Option.orElse(row, () => enclosingRow(sourceCode, fn));
|
|
338
|
+
};
|
|
339
|
+
const noKeyedRowIndexRule = Rule.define({
|
|
340
|
+
*create() {
|
|
341
|
+
const context = yield* RuleContext;
|
|
342
|
+
return { CallExpression: (node) => {
|
|
343
|
+
if (node.type !== "CallExpression" || node.callee.type !== "CallExpression" || !Option.contains(lastName(node.callee.callee), "keyed")) return Effect.void;
|
|
344
|
+
return Option.match(Option.flatMap(enclosingRow(context.sourceCode, node), (row) => Option.map(row.parameter, (parameter) => ({
|
|
345
|
+
parameter,
|
|
346
|
+
iterator: row.iterator
|
|
347
|
+
}))), {
|
|
348
|
+
onNone: () => Effect.void,
|
|
349
|
+
onSome: ({ parameter, iterator }) => context.report(Diagnostic.fromId({
|
|
350
|
+
data: { iterator },
|
|
351
|
+
messageId: "indexParameter",
|
|
352
|
+
node: parameter
|
|
353
|
+
}))
|
|
354
|
+
});
|
|
355
|
+
} };
|
|
356
|
+
},
|
|
357
|
+
meta: Rule.meta({
|
|
358
|
+
description: "A mapped h.keyed row takes no index parameter, so its key can only come from the entity",
|
|
359
|
+
messages: { indexParameter: "This `{{iterator}}` callback builds an h.keyed row and takes an index parameter. Drop the index and key the row with the entity's stable id or slug." },
|
|
360
|
+
type: "problem"
|
|
361
|
+
}),
|
|
362
|
+
name: "no-keyed-row-index"
|
|
363
|
+
});
|
|
364
|
+
// src/rules/no-manual-tagged-construction.ts
|
|
365
|
+
const noManualTaggedConstructionRule = Rule.define({
|
|
366
|
+
*create() {
|
|
367
|
+
const context = yield* RuleContext;
|
|
368
|
+
const imports = collectEffectImports(context.sourceCode);
|
|
369
|
+
return { ObjectExpression: (node) => {
|
|
370
|
+
if (node.type !== "ObjectExpression") return Effect.void;
|
|
371
|
+
if (!imports.hasTagApi || isMatchPatternObject(node, imports, context.sourceCode)) return Effect.void;
|
|
372
|
+
const property = Arr.findFirst(node.properties, (entry) => entry.type === "Property" && Option.contains(propertyName(entry), "_tag") && isStringLiteral(entry.value));
|
|
373
|
+
return Option.match(property, {
|
|
374
|
+
onNone: () => Effect.void,
|
|
375
|
+
onSome: (entry) => context.report(Diagnostic.fromId({
|
|
376
|
+
messageId: "manualConstruction",
|
|
377
|
+
node: entry
|
|
378
|
+
}))
|
|
379
|
+
});
|
|
380
|
+
} };
|
|
381
|
+
},
|
|
382
|
+
meta: Rule.meta({
|
|
383
|
+
description: "Tagged values come from their existing Effect constructors rather than hand-written `_tag` objects",
|
|
384
|
+
messages: { manualConstruction: "Use the existing Schema tagged .make, tagged class/error constructor, or Data.taggedEnum variant constructor instead of writing a literal _tag object." },
|
|
385
|
+
type: "problem"
|
|
386
|
+
}),
|
|
387
|
+
name: "no-manual-tagged-construction"
|
|
388
|
+
});
|
|
389
|
+
// src/rules/no-reexports.ts
|
|
390
|
+
const relayedRoot = (node) => {
|
|
391
|
+
if (node.type === "MemberExpression") return relayedRoot(node.object);
|
|
392
|
+
if (node.type === "TSAsExpression" || node.type === "TSSatisfiesExpression" || node.type === "TSNonNullExpression" || node.type === "ParenthesizedExpression") return relayedRoot(node.expression);
|
|
393
|
+
return node;
|
|
394
|
+
};
|
|
395
|
+
const isImported = (node, imported) => {
|
|
396
|
+
const root = Option.map(node, relayedRoot);
|
|
397
|
+
return Option.isSome(root) && root.value.type === "Identifier" && HashSet.has(imported, root.value.name);
|
|
398
|
+
};
|
|
399
|
+
const relays = (statement, imported) => {
|
|
400
|
+
if (statement.type === "ExportAllDeclaration") return [statement];
|
|
401
|
+
if (statement.type === "ExportDefaultDeclaration") return isImported(Option.some(statement.declaration), imported) ? [statement] : [];
|
|
402
|
+
if (statement.type !== "ExportNamedDeclaration") return [];
|
|
403
|
+
if (statement.source !== null) return [statement];
|
|
404
|
+
if (statement.declaration?.type === "VariableDeclaration") return Arr.filter(statement.declaration.declarations, (declarator) => isImported(Option.fromNullishOr(declarator.init), imported));
|
|
405
|
+
return Arr.filter(statement.specifiers, (specifier) => isImported(Option.some(specifier.local), imported));
|
|
406
|
+
};
|
|
407
|
+
const importedNames = (program) => HashSet.fromIterable(Arr.flatMap(program.body, (statement) => statement.type === "ImportDeclaration" ? Arr.map(statement.specifiers, (specifier) => specifier.local.name) : []));
|
|
408
|
+
const noReexportsRule = Rule.define({
|
|
409
|
+
*create() {
|
|
410
|
+
const context = yield* RuleContext;
|
|
411
|
+
return { Program: (node) => {
|
|
412
|
+
if (node.type !== "Program") return Effect.void;
|
|
413
|
+
const imported = importedNames(node);
|
|
414
|
+
return Effect.forEach(Arr.flatMap(node.body, (statement) => relays(statement, imported)), (relay) => context.report(Diagnostic.fromId({
|
|
415
|
+
messageId: "reexport",
|
|
416
|
+
node: relay
|
|
417
|
+
})), {
|
|
418
|
+
concurrency: 1,
|
|
419
|
+
discard: true
|
|
420
|
+
});
|
|
421
|
+
} };
|
|
422
|
+
},
|
|
423
|
+
meta: Rule.meta({
|
|
424
|
+
description: "Imports resolve directly to their declaring modules",
|
|
425
|
+
messages: { reexport: "Do not re-export. Import this name from the module that declares it." },
|
|
426
|
+
type: "problem"
|
|
427
|
+
}),
|
|
428
|
+
name: "no-reexports"
|
|
429
|
+
});
|
|
430
|
+
// src/rules/no-silent-error-swallow.ts
|
|
431
|
+
const handlers = (node) => {
|
|
432
|
+
if (node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression") return [node];
|
|
433
|
+
if (node.type === "ObjectExpression") return Arr.flatMap(node.properties, (property) => property.type === "Property" ? handlers(property.value) : []);
|
|
434
|
+
return [];
|
|
435
|
+
};
|
|
436
|
+
const reportSwallowedHandler = (context, imports, handler) => {
|
|
437
|
+
const { body } = handler;
|
|
438
|
+
if (body === null) return Effect.void;
|
|
439
|
+
let result = Option.some(body);
|
|
440
|
+
if (body.type === "BlockStatement") {
|
|
441
|
+
const [statement] = body.body;
|
|
442
|
+
result = body.body.length === 1 && statement?.type === "ReturnStatement" ? Option.fromNullishOr(statement.argument) : Option.none();
|
|
443
|
+
}
|
|
444
|
+
return Option.exists(result, (value) => Option.contains(effectReferenceName(value, imports, context.sourceCode), "void")) ? context.report(Diagnostic.fromId({
|
|
445
|
+
messageId: "silentSwallow",
|
|
446
|
+
node: handler
|
|
447
|
+
})) : Effect.void;
|
|
448
|
+
};
|
|
449
|
+
const noSilentErrorSwallowRule = Rule.define({
|
|
450
|
+
*create() {
|
|
451
|
+
const context = yield* RuleContext;
|
|
452
|
+
const imports = collectEffectImports(context.sourceCode);
|
|
453
|
+
return { CallExpression: (node) => {
|
|
454
|
+
if (node.type !== "CallExpression") return Effect.void;
|
|
455
|
+
const method = effectReferenceName(node.callee, imports, context.sourceCode);
|
|
456
|
+
if (Option.isNone(method) || !Str.startsWith("catch")(method.value) || method.value === "catchIf" || method.value === "catchFilter" || method.value === "catchCauseIf" || method.value === "catchCauseFilter") return Effect.void;
|
|
457
|
+
return Effect.forEach(Arr.flatMap(node.arguments, handlers), (handler) => reportSwallowedHandler(context, imports, handler), {
|
|
458
|
+
concurrency: 1,
|
|
459
|
+
discard: true
|
|
460
|
+
});
|
|
461
|
+
} };
|
|
462
|
+
},
|
|
463
|
+
meta: Rule.meta({
|
|
464
|
+
description: "Effect catch handlers handle, log or rethrow errors instead of returning only `Effect.void`",
|
|
465
|
+
messages: { silentSwallow: "Handle, log or rethrow the error instead of returning only Effect.void." },
|
|
466
|
+
type: "problem"
|
|
467
|
+
}),
|
|
468
|
+
name: "no-silent-error-swallow"
|
|
469
|
+
});
|
|
470
|
+
// src/rules/no-single-use-trivial-helpers.ts
|
|
471
|
+
const MAX_TRIVIAL_NODES = 12;
|
|
472
|
+
const AstNode = Schema.Struct({ type: Schema.String });
|
|
473
|
+
const helpersInStatement = (statement) => {
|
|
474
|
+
if (statement.type === "FunctionDeclaration") return statement.id === null ? [] : [{
|
|
475
|
+
id: statement.id,
|
|
476
|
+
name: statement.id.name,
|
|
477
|
+
node: statement
|
|
478
|
+
}];
|
|
479
|
+
if (statement.type !== "VariableDeclaration") return [];
|
|
480
|
+
return Arr.flatMap(statement.declarations, (declarator) => declarator.id.type === "Identifier" && (declarator.init?.type === "ArrowFunctionExpression" || declarator.init?.type === "FunctionExpression") ? [{
|
|
481
|
+
id: declarator.id,
|
|
482
|
+
name: declarator.id.name,
|
|
483
|
+
node: declarator.init
|
|
484
|
+
}] : []);
|
|
485
|
+
};
|
|
486
|
+
const isAstNode = Schema.is(AstNode);
|
|
487
|
+
const isFieldList = Schema.is(Schema.Array(Schema.Unknown));
|
|
488
|
+
const childNodes = (node, key) => {
|
|
489
|
+
const field = Option.getOrNull(R.get(node, key));
|
|
490
|
+
if (isFieldList(field)) return Arr.filter(field, isAstNode);
|
|
491
|
+
return isAstNode(field) ? [field] : [];
|
|
492
|
+
};
|
|
493
|
+
const nodeCount = (visitorKeys, node) => Arr.reduce(Option.getOrElse(R.get(visitorKeys, node.type), () => []), 1, (total, key) => Arr.reduce(childNodes(node, key), total, (sum, child) => sum + nodeCount(visitorKeys, child)));
|
|
494
|
+
const TYPE_WRAPPERS = HashSet.make("ParenthesizedExpression", "TSAsExpression", "TSNonNullExpression", "TSSatisfiesExpression", "TSTypeAssertion");
|
|
495
|
+
const exportsBinding = (node) => Option.exists(Option.fromNullishOr(node.parent), (parent) => HashSet.has(TYPE_WRAPPERS, parent.type) ? exportsBinding(parent) : parent.type === "ExportSpecifier" || parent.type === "ExportDefaultDeclaration");
|
|
496
|
+
const within = (outer, inner) => inner.start >= outer.start && inner.end <= outer.end;
|
|
497
|
+
const noSingleUseTrivialHelpersRule = Rule.define({
|
|
498
|
+
*create() {
|
|
499
|
+
const context = yield* RuleContext;
|
|
500
|
+
const { sourceCode } = context;
|
|
501
|
+
const variableOf = (helper) => Arr.findFirst(sourceCode.getDeclaredVariables(helper.id.parent), (variable) => Arr.some(variable.identifiers, (identifier) => identifier.start === helper.id.start));
|
|
502
|
+
const usedOnceFromOutside = (helper) => Option.exists(variableOf(helper), (variable) => {
|
|
503
|
+
const uses = Arr.filter(variable.references, (reference) => !reference.init);
|
|
504
|
+
return uses.length === 1 && Arr.every(uses, (reference) => !within(helper.node, reference.identifier) && !exportsBinding(reference.identifier));
|
|
505
|
+
});
|
|
506
|
+
const isTrivial = (helper) => helper.node.body !== null && nodeCount(sourceCode.visitorKeys, helper.node.body) <= MAX_TRIVIAL_NODES;
|
|
507
|
+
return { "Program:exit": () => Effect.forEach(Arr.filter(Arr.flatMap(sourceCode.ast.body, helpersInStatement), (helper) => usedOnceFromOutside(helper) && isTrivial(helper)), (helper) => context.report(Diagnostic.fromId({
|
|
508
|
+
data: { name: helper.name },
|
|
509
|
+
messageId: "singleUse",
|
|
510
|
+
node: helper.node
|
|
511
|
+
})), {
|
|
512
|
+
concurrency: 1,
|
|
513
|
+
discard: true
|
|
514
|
+
}) };
|
|
515
|
+
},
|
|
516
|
+
meta: Rule.meta({
|
|
517
|
+
description: "Top-level file-local helpers used once whose body has at most twelve AST nodes are inlined",
|
|
518
|
+
messages: { singleUse: "Helper '{{name}}' is tiny and used once. Inline it instead of adding another hop." },
|
|
519
|
+
type: "problem"
|
|
520
|
+
}),
|
|
521
|
+
name: "no-single-use-trivial-helpers"
|
|
522
|
+
});
|
|
523
|
+
// src/shared/foldkit-api.ts
|
|
524
|
+
const NAMESPACES = HashMap.make(["foldkit", []], ["foldkit/command", ["Command"]], ["foldkit/html", ["Html"]], ["foldkit/message", ["Message"]], ["foldkit/scene", ["Scene"]], ["foldkit/schema", ["Schema"]], ["foldkit/test", []]);
|
|
525
|
+
const isFoldkitCall = (sourceCode, node, ...wanted) => Option.exists(importedPath(sourceCode, node.callee), (path) => Option.exists(HashMap.get(NAMESPACES, path.source), (prefix) => {
|
|
526
|
+
const full = Arr.join([...prefix, ...path.members], ".");
|
|
527
|
+
return Arr.some(wanted, (candidate) => Arr.join(candidate, ".") === full);
|
|
528
|
+
}));
|
|
529
|
+
const textWithHoles = dual(2, (node, hole) => {
|
|
530
|
+
if (isStringLiteral(node)) return Option.some(node.value);
|
|
531
|
+
return node.type === "TemplateLiteral" ? Option.some(Arr.join(Arr.map(node.quasis, (quasi) => quasi.value.raw), hole)) : Option.none();
|
|
532
|
+
});
|
|
533
|
+
// src/rules/prefer-accessible-scene-locators.ts
|
|
534
|
+
const ROLE_TAGS = HashSet.make("a", "article", "aside", "button", "datalist", "dd", "details", "dialog", "dt", "fieldset", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "img", "input", "li", "main", "menu", "meter", "nav", "ol", "option", "output", "progress", "select", "summary", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "tr", "ul");
|
|
535
|
+
const ACCESSIBLE_ATTRIBUTES = /\[\s*(?:role|aria-label|aria-labelledby|alt|placeholder|title)\s*(?:[~|^$*]?=|\])/iu;
|
|
536
|
+
const QUOTED = /"[^"]*"|'[^']*'/gu;
|
|
537
|
+
const COMBINATOR = /[\s>+~]/u;
|
|
538
|
+
const TAG = /^[a-z][a-z0-9-]*/iu;
|
|
539
|
+
const SUBJECT_PSEUDO = /^(?:is|where|matches)\(/u;
|
|
540
|
+
const splitTopLevel = (text, isSeparator) => Arr.reduce(Arr.filter(Str.split(text, ""), Str.isNonEmpty), {
|
|
541
|
+
depth: 0,
|
|
542
|
+
parts: [""]
|
|
543
|
+
}, ({ depth, parts }, char) => {
|
|
544
|
+
if (depth === 0 && isSeparator(char)) return {
|
|
545
|
+
depth,
|
|
546
|
+
parts: [...parts, ""]
|
|
547
|
+
};
|
|
548
|
+
const opened = char === "(" || char === "[" ? 1 : 0;
|
|
549
|
+
const closed = char === ")" || char === "]" ? 1 : 0;
|
|
550
|
+
return {
|
|
551
|
+
depth: depth + opened - closed,
|
|
552
|
+
parts: [...parts.slice(0, -1), `${parts.at(-1) ?? ""}${char}`]
|
|
553
|
+
};
|
|
554
|
+
}).parts;
|
|
555
|
+
const fitsAccessibleLocator = (selector) => Arr.some(splitTopLevel(selector, (char) => char === ","), (part) => {
|
|
556
|
+
const compound = Option.getOrElse(Arr.last(Arr.filter(splitTopLevel(Str.trim(part), (char) => COMBINATOR.test(char)), (piece) => piece !== "")), () => "");
|
|
557
|
+
const [tag = ""] = TAG.exec(compound) ?? [];
|
|
558
|
+
return HashSet.has(ROLE_TAGS, Str.toLowerCase(tag)) || Arr.some(splitTopLevel(compound, (char) => char === ":"), (piece) => {
|
|
559
|
+
const open = Str.indexOf("(")(piece);
|
|
560
|
+
if (Option.isNone(open)) return ACCESSIBLE_ATTRIBUTES.test(piece);
|
|
561
|
+
const close = Str.lastIndexOf(")")(piece).pipe(Option.getOrElse(() => -1));
|
|
562
|
+
return ACCESSIBLE_ATTRIBUTES.test(`${Str.slice(0, open.value)(piece)}${Str.slice(close + 1)(piece)}`) || SUBJECT_PSEUDO.test(piece) && fitsAccessibleLocator(Str.slice(open.value + 1, close)(piece));
|
|
563
|
+
});
|
|
564
|
+
});
|
|
565
|
+
const preferAccessibleSceneLocatorsRule = Rule.define({
|
|
566
|
+
*create() {
|
|
567
|
+
const context = yield* RuleContext;
|
|
568
|
+
return { CallExpression: (node) => {
|
|
569
|
+
if (node.type !== "CallExpression" || !isFoldkitCall(context.sourceCode, node, ["Scene", "selector"], ["Scene", "allSelector"], [
|
|
570
|
+
"Scene",
|
|
571
|
+
"all",
|
|
572
|
+
"selector"
|
|
573
|
+
])) return Effect.void;
|
|
574
|
+
const [css] = node.arguments;
|
|
575
|
+
if (css === void 0) return Effect.void;
|
|
576
|
+
return Option.match(Option.filter(textWithHoles(css, "x"), (text) => fitsAccessibleLocator(Str.replaceAll(QUOTED, "\"\"")(text))), {
|
|
577
|
+
onNone: () => Effect.void,
|
|
578
|
+
onSome: () => context.report(Diagnostic.fromId({
|
|
579
|
+
data: { target: context.sourceCode.getText(css) },
|
|
580
|
+
messageId: "accessibleLocator",
|
|
581
|
+
node
|
|
582
|
+
}))
|
|
583
|
+
});
|
|
584
|
+
} };
|
|
585
|
+
},
|
|
586
|
+
meta: Rule.meta({
|
|
587
|
+
description: "Scene tests find elements by role, label or text, keeping selector() for targets no accessible locator fits",
|
|
588
|
+
messages: { accessibleLocator: "{{target}} targets an element with an accessible name or role. Find it with Scene.role, Scene.label, Scene.text, Scene.altText or Scene.title instead of a CSS selector." },
|
|
589
|
+
type: "suggestion"
|
|
590
|
+
}),
|
|
591
|
+
name: "prefer-accessible-scene-locators"
|
|
592
|
+
});
|
|
593
|
+
// src/rules/require-command-answer-names.ts
|
|
594
|
+
const OUTCOMES = [
|
|
595
|
+
"Completed",
|
|
596
|
+
"Succeeded",
|
|
597
|
+
"Failed"
|
|
598
|
+
];
|
|
599
|
+
const answersOf = (call) => {
|
|
600
|
+
const [name] = call.arguments;
|
|
601
|
+
const list = Option.flatMap(Option.map(Arr.get(call.arguments, 1), unwrapExpression), (settings) => Arr.findFirst(settings.type === "ObjectExpression" ? settings.properties : [], (property) => {
|
|
602
|
+
const value = property.type === "Property" && Option.contains(propertyName(property), "messages") ? unwrapExpression(property.value) : property;
|
|
603
|
+
return value.type === "ArrayExpression" ? Option.some(value) : Option.none();
|
|
604
|
+
}));
|
|
605
|
+
const command = name !== void 0 && isStringLiteral(name) ? Option.some(name.value) : Option.none();
|
|
606
|
+
return Option.map(Option.all([command, list]), ([text, array]) => ({
|
|
607
|
+
command: text,
|
|
608
|
+
list: array,
|
|
609
|
+
answers: Arr.flatMap(array.elements, (element) => element === null || element.type === "SpreadElement" ? [] : Arr.fromOption(Option.map(lastName(element), (answer) => ({
|
|
610
|
+
name: answer,
|
|
611
|
+
node: element,
|
|
612
|
+
outcome: Arr.findFirst(OUTCOMES, (outcome) => answer === `${outcome}${text}`)
|
|
613
|
+
}))))
|
|
614
|
+
}));
|
|
615
|
+
};
|
|
616
|
+
const requireCommandAnswerNamesRule = Rule.define({
|
|
617
|
+
*create() {
|
|
618
|
+
const context = yield* RuleContext;
|
|
619
|
+
const check = ({ command, list, answers }) => {
|
|
620
|
+
const outcomes = HashSet.fromIterable(Arr.flatMap(answers, ({ outcome }) => Arr.fromOption(outcome)));
|
|
621
|
+
const mixed = HashSet.has(outcomes, "Completed") && (HashSet.has(outcomes, "Succeeded") || HashSet.has(outcomes, "Failed"));
|
|
622
|
+
return Effect.andThen(Effect.forEach(Arr.filter(answers, ({ outcome }) => Option.isNone(outcome)), ({ name, node }) => context.report(Diagnostic.fromId({
|
|
623
|
+
data: {
|
|
624
|
+
command,
|
|
625
|
+
name
|
|
626
|
+
},
|
|
627
|
+
messageId: "wrongAnswer",
|
|
628
|
+
node
|
|
629
|
+
})), {
|
|
630
|
+
concurrency: 1,
|
|
631
|
+
discard: true
|
|
632
|
+
}), mixed ? context.report(Diagnostic.fromId({
|
|
633
|
+
data: { command },
|
|
634
|
+
messageId: "mixedAnswers",
|
|
635
|
+
node: list
|
|
636
|
+
})) : Effect.void);
|
|
637
|
+
};
|
|
638
|
+
return { CallExpression: (node) => node.type === "CallExpression" && isFoldkitCall(context.sourceCode, node, ["Command", "define"]) ? Option.match(answersOf(node), {
|
|
639
|
+
onNone: () => Effect.void,
|
|
640
|
+
onSome: check
|
|
641
|
+
}) : Effect.void };
|
|
642
|
+
},
|
|
643
|
+
meta: Rule.meta({
|
|
644
|
+
description: "A Command X is answered only by CompletedX, or by SucceededX and FailedX",
|
|
645
|
+
messages: {
|
|
646
|
+
mixedAnswers: "Command `{{command}}` answers both Completed{{command}} and Succeeded{{command}} or Failed{{command}}. An infallible Command answers Completed{{command}}; a fallible one answers Succeeded{{command}} or Failed{{command}}.",
|
|
647
|
+
wrongAnswer: "Command `{{command}}` answers `{{name}}`. Name its result Completed{{command}} if it can't fail, or Succeeded{{command}} and Failed{{command}} if it can."
|
|
648
|
+
},
|
|
649
|
+
type: "suggestion"
|
|
650
|
+
}),
|
|
651
|
+
name: "require-command-answer-names"
|
|
652
|
+
});
|
|
653
|
+
// src/rules/require-past-tense-messages.ts
|
|
654
|
+
const IRREGULAR_PAST = HashSet.make("Ate", "Became", "Began", "Bought", "Broke", "Brought", "Built", "Came", "Caught", "Chose", "Did", "Drew", "Drove", "Fell", "Felt", "Fled", "Flew", "Forgot", "Found", "Froze", "Gave", "Got", "Grew", "Had", "Heard", "Held", "Hid", "Hung", "Kept", "Knew", "Laid", "Led", "Left", "Lent", "Lost", "Made", "Meant", "Met", "Paid", "Ran", "Rang", "Rode", "Rose", "Said", "Sang", "Sank", "Sat", "Saw", "Sent", "Shook", "Shot", "Slept", "Slid", "Sold", "Sought", "Spent", "Spoke", "Stole", "Stood", "Struck", "Stuck", "Swept", "Swung", "Taught", "Thought", "Threw", "Told", "Took", "Tore", "Understood", "Undid", "Went", "Withdrew", "Woke", "Won", "Wore", "Wrote");
|
|
655
|
+
const PRESENT_ENDING_IN_ED = HashSet.make("Bed", "Bleed", "Breed", "Embed", "Exceed", "Feed", "Heed", "Need", "Proceed", "Red", "Seed", "Shed", "Shred", "Speed", "Succeed", "Weed");
|
|
656
|
+
const IMPERATIVE = /^(?:Set|Mutate)(?![a-z])/u;
|
|
657
|
+
const NO_OP = /^no[-_]?op$/iu;
|
|
658
|
+
const FIRST_WORD = /^[A-Z][a-z]*/u;
|
|
659
|
+
const problemOf = (name) => {
|
|
660
|
+
if (NO_OP.test(name)) return Option.some("noOp");
|
|
661
|
+
if (IMPERATIVE.test(name)) return Option.some("imperative");
|
|
662
|
+
const [word = ""] = FIRST_WORD.exec(name) ?? [];
|
|
663
|
+
return HashSet.has(IRREGULAR_PAST, word) || Str.endsWith("ed")(word) && !HashSet.has(PRESENT_ENDING_IN_ED, word) ? Option.none() : Option.some("notPastTense");
|
|
664
|
+
};
|
|
665
|
+
const requirePastTenseMessagesRule = Rule.define({
|
|
666
|
+
*create() {
|
|
667
|
+
const context = yield* RuleContext;
|
|
668
|
+
const reportKey = (property) => {
|
|
669
|
+
if (property.type !== "Property") return Effect.void;
|
|
670
|
+
return Option.match(Option.flatMap(propertyName(property), (name) => Option.map(problemOf(name), (messageId) => ({
|
|
671
|
+
messageId,
|
|
672
|
+
name
|
|
673
|
+
}))), {
|
|
674
|
+
onNone: () => Effect.void,
|
|
675
|
+
onSome: ({ messageId, name }) => context.report(Diagnostic.fromId({
|
|
676
|
+
data: { name },
|
|
677
|
+
messageId,
|
|
678
|
+
node: property.key
|
|
679
|
+
}))
|
|
680
|
+
});
|
|
681
|
+
};
|
|
682
|
+
return { CallExpression: (node) => {
|
|
683
|
+
if (node.type !== "CallExpression" || !isFoldkitCall(context.sourceCode, node, ["Message", "defineMessageUnion"], ["Schema", "defineMessageUnion"])) return Effect.void;
|
|
684
|
+
return Option.match(Option.map(Arr.head(node.arguments), unwrapExpression), {
|
|
685
|
+
onNone: () => Effect.void,
|
|
686
|
+
onSome: (cases) => cases.type === "ObjectExpression" ? Effect.forEach(cases.properties, reportKey, {
|
|
687
|
+
concurrency: 1,
|
|
688
|
+
discard: true
|
|
689
|
+
}) : Effect.void
|
|
690
|
+
});
|
|
691
|
+
} };
|
|
692
|
+
},
|
|
693
|
+
meta: Rule.meta({
|
|
694
|
+
description: "Every Message union key is a past-tense fact with its source prefix, never NoOp, Set* or Mutate*",
|
|
695
|
+
messages: {
|
|
696
|
+
imperative: "`{{name}}` is an imperative name. Name the Message for the fact that happened, with its source prefix: Clicked*, Updated*, Pressed*, Submitted*, Got*, Completed*, Succeeded* or Failed*.",
|
|
697
|
+
noOp: "`{{name}}` is a NoOp Message. Return the Model unchanged from the Message that happened instead of sending a Message that means nothing.",
|
|
698
|
+
notPastTense: "`{{name}}` doesn't start with a past-tense source prefix. Name the Message for the fact that happened: Clicked*, Updated*, Pressed*, Submitted*, Got*, Completed*, Succeeded* or Failed*."
|
|
699
|
+
},
|
|
700
|
+
type: "suggestion"
|
|
701
|
+
}),
|
|
702
|
+
name: "require-past-tense-messages"
|
|
703
|
+
});
|
|
704
|
+
// src/rules/require-readable-spacing.ts
|
|
705
|
+
const ELIGIBLE_SIBLINGS = {
|
|
706
|
+
BlockStatement: true,
|
|
707
|
+
BreakStatement: true,
|
|
708
|
+
ClassDeclaration: true,
|
|
709
|
+
ContinueStatement: true,
|
|
710
|
+
DebuggerStatement: true,
|
|
711
|
+
DoWhileStatement: true,
|
|
712
|
+
EmptyStatement: true,
|
|
713
|
+
ExportAllDeclaration: true,
|
|
714
|
+
ExportDefaultDeclaration: true,
|
|
715
|
+
ExportNamedDeclaration: true,
|
|
716
|
+
ExpressionStatement: true,
|
|
717
|
+
ForInStatement: true,
|
|
718
|
+
ForOfStatement: true,
|
|
719
|
+
ForStatement: true,
|
|
720
|
+
FunctionDeclaration: true,
|
|
721
|
+
IfStatement: true,
|
|
722
|
+
ImportDeclaration: true,
|
|
723
|
+
LabeledStatement: true,
|
|
724
|
+
ReturnStatement: true,
|
|
725
|
+
SwitchCase: true,
|
|
726
|
+
SwitchStatement: true,
|
|
727
|
+
TSCallSignatureDeclaration: true,
|
|
728
|
+
TSConstructSignatureDeclaration: true,
|
|
729
|
+
TSDeclareFunction: true,
|
|
730
|
+
TSEnumDeclaration: true,
|
|
731
|
+
TSImportEqualsDeclaration: true,
|
|
732
|
+
TSInterfaceDeclaration: true,
|
|
733
|
+
TSMethodSignature: true,
|
|
734
|
+
TSModuleDeclaration: true,
|
|
735
|
+
TSNamespaceExportDeclaration: true,
|
|
736
|
+
TSTypeAliasDeclaration: true,
|
|
737
|
+
ThrowStatement: true,
|
|
738
|
+
TryStatement: true,
|
|
739
|
+
VariableDeclaration: true,
|
|
740
|
+
WhileStatement: true,
|
|
741
|
+
WithStatement: true
|
|
742
|
+
};
|
|
743
|
+
const DECLARATION_KEYWORDS = {
|
|
744
|
+
ClassDeclaration: "class",
|
|
745
|
+
TSInterfaceDeclaration: "interface",
|
|
746
|
+
TSTypeAliasDeclaration: "type"
|
|
747
|
+
};
|
|
748
|
+
const CONTROL_FLOW_KEYWORDS = {
|
|
749
|
+
DoWhileStatement: "do",
|
|
750
|
+
ForInStatement: "for",
|
|
751
|
+
ForOfStatement: "for",
|
|
752
|
+
ForStatement: "for",
|
|
753
|
+
IfStatement: "if",
|
|
754
|
+
ReturnStatement: "return",
|
|
755
|
+
SwitchStatement: "switch",
|
|
756
|
+
TryStatement: "try",
|
|
757
|
+
WhileStatement: "while"
|
|
758
|
+
};
|
|
759
|
+
const unwrapLabels = (node) => node.type === "LabeledStatement" ? unwrapLabels(node.body) : node;
|
|
760
|
+
const isSameLine = (left, right) => left.loc.end.line === right.loc.start.line;
|
|
761
|
+
const isSemicolonToken = (token) => token.type === "Punctuator" && token.value === ";";
|
|
762
|
+
const firstTokenValue = (source, node) => {
|
|
763
|
+
const token = source.getFirstToken(node);
|
|
764
|
+
if (token === null) throw new Cause.NoSuchElementError("Statement has no first token");
|
|
765
|
+
return token.value;
|
|
766
|
+
};
|
|
767
|
+
const actualLastToken = (source, node) => {
|
|
768
|
+
const lastToken = source.getLastToken(node);
|
|
769
|
+
if (lastToken === null) throw new Cause.NoSuchElementError("Statement has no last token");
|
|
770
|
+
const previousToken = source.getTokenBefore(lastToken);
|
|
771
|
+
const nextToken = source.getTokenAfter(lastToken);
|
|
772
|
+
if (previousToken !== null && nextToken !== null && previousToken.range[0] >= node.range[0] && isSemicolonToken(lastToken) && !isSameLine(previousToken, lastToken) && isSameLine(lastToken, nextToken)) return previousToken;
|
|
773
|
+
return lastToken;
|
|
774
|
+
};
|
|
775
|
+
const isIifeStatement = (node) => {
|
|
776
|
+
if (node.type !== "ExpressionStatement") return false;
|
|
777
|
+
let expression = node.expression.type === "ChainExpression" ? node.expression.expression : node.expression;
|
|
778
|
+
if (expression.type === "UnaryExpression") expression = expression.argument.type === "ChainExpression" ? expression.argument.expression : expression.argument;
|
|
779
|
+
if (expression.type !== "CallExpression") return false;
|
|
780
|
+
const unwrapSequence = (callee) => {
|
|
781
|
+
if (callee.type !== "SequenceExpression") return callee;
|
|
782
|
+
const lastExpression = callee.expressions.at(-1);
|
|
783
|
+
if (lastExpression === void 0) throw new Cause.NoSuchElementError("Sequence expression is empty");
|
|
784
|
+
return unwrapSequence(lastExpression);
|
|
785
|
+
};
|
|
786
|
+
const callee = unwrapSequence(expression.callee);
|
|
787
|
+
return callee.type === "FunctionExpression" || callee.type === "ArrowFunctionExpression" || callee.type === "FunctionDeclaration";
|
|
788
|
+
};
|
|
789
|
+
const isBlockLike = (source, node) => {
|
|
790
|
+
if (node.type === "DoWhileStatement" && node.body.type === "BlockStatement") return true;
|
|
791
|
+
if (isIifeStatement(node)) return true;
|
|
792
|
+
const lastToken = source.getLastToken(node, (token) => !isSemicolonToken(token));
|
|
793
|
+
if (lastToken?.type !== "Punctuator" || lastToken.value !== "}") return false;
|
|
794
|
+
const owner = source.getNodeByRangeIndex(lastToken.range[0]);
|
|
795
|
+
return owner?.type === "BlockStatement" || owner?.type === "SwitchStatement";
|
|
796
|
+
};
|
|
797
|
+
const isMultilineBinding = (source, node) => node.type === "VariableDeclaration" && node.loc.start.line !== node.loc.end.line && (node.kind === "using" || node.kind === "await using" || firstTokenValue(source, node) === node.kind);
|
|
798
|
+
const opensWithKeyword = (source, node, table) => {
|
|
799
|
+
const keyword = table[node.type];
|
|
800
|
+
return keyword !== void 0 && firstTokenValue(source, node) === keyword;
|
|
801
|
+
};
|
|
802
|
+
const isReadableDeclaration = (source, node) => node.type === "FunctionDeclaration" || opensWithKeyword(source, node, DECLARATION_KEYWORDS);
|
|
803
|
+
const overloadKind = (node) => {
|
|
804
|
+
const declaration = node.type === "ExportNamedDeclaration" ? node.declaration : node;
|
|
805
|
+
if (declaration?.type === "TSDeclareFunction") return "overload";
|
|
806
|
+
if (declaration?.type === "FunctionDeclaration") return "implementation";
|
|
807
|
+
return "other";
|
|
808
|
+
};
|
|
809
|
+
const isOverloadPair = (previous, next) => overloadKind(previous) === "overload" && ["overload", "implementation"].includes(overloadKind(next));
|
|
810
|
+
const isProgramNonImport = (node) => node.type !== "Program" && node.parent.type === "Program" && node.type !== "ImportDeclaration";
|
|
811
|
+
const requiresBlankLine = (source, previousNode, nextNode) => {
|
|
812
|
+
const previous = unwrapLabels(previousNode);
|
|
813
|
+
const next = unwrapLabels(nextNode);
|
|
814
|
+
const previousImport = previous.type === "ImportDeclaration" && firstTokenValue(source, previous) === "import";
|
|
815
|
+
if (isOverloadPair(previous, next) || previousImport && next.type === "ImportDeclaration" && firstTokenValue(source, next) === "import") return false;
|
|
816
|
+
return previousImport || isProgramNonImport(previous) || isProgramNonImport(next) || isReadableDeclaration(source, previous) || isReadableDeclaration(source, next) || isMultilineBinding(source, previous) || isMultilineBinding(source, next) || opensWithKeyword(source, next, CONTROL_FLOW_KEYWORDS) || isBlockLike(source, previous);
|
|
817
|
+
};
|
|
818
|
+
const findInsertion = (source, previous, next) => {
|
|
819
|
+
let anchor = actualLastToken(source, previous);
|
|
820
|
+
const scanTokens = (cursor) => {
|
|
821
|
+
if (cursor.range[0] >= next.range[0]) return false;
|
|
822
|
+
const token = source.getTokenAfter(cursor, { includeComments: true });
|
|
823
|
+
if (token === null) throw new Cause.NoSuchElementError("Sibling tokens are discontinuous");
|
|
824
|
+
return token.loc.start.line - cursor.loc.end.line >= 2 || scanTokens(token);
|
|
825
|
+
};
|
|
826
|
+
if (next.loc.start.line - anchor.loc.end.line >= 2 && scanTokens(anchor)) return Option.none();
|
|
827
|
+
const firstToken = source.getFirstTokenBetween(anchor, next, {
|
|
828
|
+
filter: (token) => {
|
|
829
|
+
if (isSameLine(anchor, token)) {
|
|
830
|
+
anchor = token;
|
|
831
|
+
return false;
|
|
832
|
+
}
|
|
833
|
+
return true;
|
|
834
|
+
},
|
|
835
|
+
includeComments: true
|
|
836
|
+
});
|
|
837
|
+
return Option.some({
|
|
838
|
+
after: anchor,
|
|
839
|
+
text: isSameLine(anchor, firstToken ?? next) ? "\n\n" : "\n"
|
|
840
|
+
});
|
|
841
|
+
};
|
|
842
|
+
const reportLocation = (source, node) => {
|
|
843
|
+
if (node.loc.start.line === node.loc.end.line) return node.loc;
|
|
844
|
+
const sourceLine = source.lines[node.loc.start.line - 1];
|
|
845
|
+
if (sourceLine === void 0) throw new Cause.NoSuchElementError("Statement source line is missing");
|
|
846
|
+
return {
|
|
847
|
+
end: {
|
|
848
|
+
column: sourceLine.length,
|
|
849
|
+
line: node.loc.start.line
|
|
850
|
+
},
|
|
851
|
+
start: node.loc.start
|
|
852
|
+
};
|
|
853
|
+
};
|
|
854
|
+
const previousSibling = (nodes, index) => Arr.findLast(nodes.slice(0, index), (sibling) => Boolean(ELIGIBLE_SIBLINGS[sibling.type]));
|
|
855
|
+
const reportSibling = (context, nodes, node, index) => {
|
|
856
|
+
const source = context.sourceCode;
|
|
857
|
+
if (ELIGIBLE_SIBLINGS[node.type] !== true) return Effect.void;
|
|
858
|
+
const previous = previousSibling(nodes, index);
|
|
859
|
+
if (Option.isNone(previous) || !requiresBlankLine(source, previous.value, node)) return Effect.void;
|
|
860
|
+
const insertion = findInsertion(source, previous.value, node);
|
|
861
|
+
if (Option.isNone(insertion)) return Effect.void;
|
|
862
|
+
return context.report(Diagnostic.withFix({
|
|
863
|
+
...Diagnostic.fromId({
|
|
864
|
+
messageId: "expectedBlankLine",
|
|
865
|
+
node
|
|
866
|
+
}),
|
|
867
|
+
loc: reportLocation(source, node)
|
|
868
|
+
}, Diagnostic.insertAfter(insertion.value.after, insertion.value.text)));
|
|
869
|
+
};
|
|
870
|
+
const requireReadableSpacingRule = Rule.define({
|
|
871
|
+
*create() {
|
|
872
|
+
const context = yield* RuleContext;
|
|
873
|
+
const scan = (nodes) => Effect.forEach(nodes, (node, index) => reportSibling(context, nodes, node, index), {
|
|
874
|
+
concurrency: 1,
|
|
875
|
+
discard: true
|
|
876
|
+
});
|
|
877
|
+
const visitContainer = (node) => {
|
|
878
|
+
if (node.type === "SwitchCase") return scan(node.consequent);
|
|
879
|
+
if (node.type === "SwitchStatement") return scan(node.cases);
|
|
880
|
+
if (node.type === "TSTypeLiteral") return scan(node.members);
|
|
881
|
+
return node.type === "BlockStatement" || node.type === "Program" || node.type === "StaticBlock" || node.type === "TSInterfaceBody" || node.type === "TSModuleBlock" ? scan(node.body) : Effect.void;
|
|
882
|
+
};
|
|
883
|
+
return {
|
|
884
|
+
BlockStatement: visitContainer,
|
|
885
|
+
Program: visitContainer,
|
|
886
|
+
StaticBlock: visitContainer,
|
|
887
|
+
SwitchCase: visitContainer,
|
|
888
|
+
SwitchStatement: visitContainer,
|
|
889
|
+
TSInterfaceBody: visitContainer,
|
|
890
|
+
TSModuleBlock: visitContainer,
|
|
891
|
+
TSTypeLiteral: visitContainer
|
|
892
|
+
};
|
|
893
|
+
},
|
|
894
|
+
meta: {
|
|
895
|
+
...Rule.meta({
|
|
896
|
+
description: "Readable spacing between declarations and logical statement groups",
|
|
897
|
+
fixable: "whitespace",
|
|
898
|
+
messages: { expectedBlankLine: "Expected blank line before this statement." },
|
|
899
|
+
type: "layout"
|
|
900
|
+
}),
|
|
901
|
+
schema: []
|
|
902
|
+
},
|
|
903
|
+
name: "require-readable-spacing"
|
|
904
|
+
});
|
|
905
|
+
// src/plugin.ts
|
|
906
|
+
const plugin = Plugin.define({
|
|
907
|
+
name: "birbprophet",
|
|
908
|
+
rules: {
|
|
909
|
+
"no-ambient-crypto": noAmbientCryptoRule,
|
|
910
|
+
"no-array-filter-map": noArrayFilterMapRule,
|
|
911
|
+
"no-comments": noCommentsRule,
|
|
912
|
+
"no-impure-update-file": noImpureUpdateFileRule,
|
|
913
|
+
"no-impure-view-file": noImpureViewFileRule,
|
|
914
|
+
"no-inline-exported-object-types": noInlineExportedObjectTypesRule,
|
|
915
|
+
"no-keyed-row-index": noKeyedRowIndexRule,
|
|
916
|
+
"no-manual-tagged-construction": noManualTaggedConstructionRule,
|
|
917
|
+
"no-reexports": noReexportsRule,
|
|
918
|
+
"no-silent-error-swallow": noSilentErrorSwallowRule,
|
|
919
|
+
"no-single-use-trivial-helpers": noSingleUseTrivialHelpersRule,
|
|
920
|
+
"prefer-accessible-scene-locators": preferAccessibleSceneLocatorsRule,
|
|
921
|
+
"require-command-answer-names": requireCommandAnswerNamesRule,
|
|
922
|
+
"require-past-tense-messages": requirePastTenseMessagesRule,
|
|
923
|
+
"require-readable-spacing": requireReadableSpacingRule
|
|
924
|
+
},
|
|
925
|
+
specifier: "@milkenjoyer/toolchain/plugin"
|
|
926
|
+
});
|
|
927
|
+
export { plugin as t };
|