@stateward/plugin-errors 1.2.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -8
- package/dist/catch-hides-unexpected.d.ts +4 -1
- package/dist/catch-hides-unexpected.js +87 -11
- package/dist/catch-misses-error.d.ts +1 -1
- package/dist/catch-misses-error.js +63 -20
- package/dist/finally-can-throw.js +46 -6
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -0
- package/dist/inference/analysis.d.ts +109 -0
- package/dist/inference/analysis.js +170 -0
- package/dist/inference/builtins.d.ts +7 -2
- package/dist/inference/builtins.js +20 -33
- package/dist/inference/deps.js +2 -2
- package/dist/inference/needs.d.ts +16 -0
- package/dist/inference/needs.js +27 -0
- package/dist/inference/packages.d.ts +24 -32
- package/dist/inference/packages.js +156 -675
- package/dist/inference/project.d.ts +2 -2
- package/dist/inference/project.js +3 -2
- package/dist/inference/solve.d.ts +29 -4
- package/dist/inference/solve.js +34 -5
- package/dist/inference/summarize.d.ts +28 -15
- package/dist/inference/summarize.js +339 -135
- package/dist/inference/summary.d.ts +46 -5
- package/dist/inference/summary.js +89 -13
- package/dist/inference/unreachable.d.ts +5 -0
- package/dist/inference/unreachable.js +160 -0
- package/dist/must-handle-error.d.ts +2 -1
- package/dist/must-handle-error.js +4 -4
- package/dist/narrow-try.d.ts +2 -0
- package/dist/narrow-try.js +62 -7
- package/dist/plugin.d.ts +12 -2
- package/dist/plugin.js +4 -2
- package/dist/react/fallbacks.js +35 -14
- package/dist/react/tree.d.ts +10 -0
- package/dist/react/tree.js +54 -7
- package/dist/refactors.js +35 -2
- package/dist/render-throw-without-boundary.d.ts +13 -4
- package/dist/render-throw-without-boundary.js +100 -10
- package/dist/result-ignored.d.ts +4 -1
- package/dist/result-ignored.js +51 -10
- package/dist/result-type.d.ts +2 -0
- package/dist/result-type.js +8 -2
- package/dist/result-unchecked.d.ts +4 -1
- package/dist/result-unchecked.js +320 -96
- package/dist/rules.meta.d.ts +29 -14
- package/dist/rules.meta.js +19 -14
- package/dist/syntax.d.ts +0 -13
- package/dist/syntax.js +0 -79
- package/dist/text.d.ts +15 -2
- package/dist/text.js +28 -5
- package/dist/throws-doc-mismatch.d.ts +1 -1
- package/dist/throws-doc-mismatch.js +59 -5
- package/dist/throws-reads.d.ts +3 -0
- package/dist/throws-reads.js +108 -0
- package/package.json +2 -2
package/dist/result-unchecked.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import ts from "@stateward/core/typescript";
|
|
2
|
-
import { defineRule } from "@stateward/core";
|
|
3
|
-
import { example, resultShapeOf, shorten } from "./result-type.js";
|
|
2
|
+
import { codeOnOneLine, defineRule, matchesName, option, offByDefaultText } from "@stateward/core";
|
|
3
|
+
import { example, freeName, resultShapeOf, shorten } from "./result-type.js";
|
|
4
|
+
/** Off by default since 1.3: 0 of 5 of its findings checked on real projects were right. */
|
|
5
|
+
const OFF_BY_DEFAULT = { since: "1.3", right: 0, checked: 5 };
|
|
4
6
|
const EXPLAIN = `# errors/result-unchecked
|
|
5
7
|
|
|
6
8
|
A call that returns its failure instead of throwing never reaches the \`catch\`; without a check, the code after it runs as if the call worked.
|
|
@@ -36,7 +38,9 @@ export async function submit(values: string): Promise<void> {
|
|
|
36
38
|
}
|
|
37
39
|
\`\`\`
|
|
38
40
|
|
|
39
|
-
For an RTK Query trigger, add \`.unwrap()\` so a failure throws: \`await deletePlan(id).unwrap()\`. Where the result is dropped, a quick fix adds it.
|
|
41
|
+
For an RTK Query trigger, add \`.unwrap()\` so a failure throws: \`await deletePlan(id).unwrap()\`. Where the result is dropped, a quick fix adds it; outside a \`try\` with a \`catch\` the thrown failure needs one around it, or a caller that catches. The message names three readings: the \`.unwrap()\`, a check (\`if ("error" in result) throw result.error;\` inside a \`try\`, so the \`catch\` and its rollback run; a stop outside one), and an \`else\` for the success path when the lines after the call should run either way.
|
|
42
|
+
|
|
43
|
+
Where the check is there and the code goes on after it, the message offers two readings: end the branch that handles the failure (a \`return\` in a function that returns nothing, a \`throw\` of the error inside a \`try\` with a \`catch\` so its rollback runs, and in words where the function returns a value), or an \`else\` for the success path when the lines after the \`if\` should run either way. Where only \`data\` is taken out of the result, there is nothing to check: the message says to keep the whole result, check it, then take \`data\` out of it.
|
|
40
44
|
|
|
41
45
|
## Why it matters
|
|
42
46
|
|
|
@@ -44,7 +48,7 @@ Some calls do not throw when they fail: they resolve to data or an error. An RTK
|
|
|
44
48
|
|
|
45
49
|
## When it says “not checked”
|
|
46
50
|
|
|
47
|
-
An \`if\` that tests the result in a way stateward cannot read (\`if (result.error && isApiError(result.error))\`) is listed as a place not checked. Test it in one of the ways below, then narrow further inside.
|
|
51
|
+
An \`if\` that tests the result in a way stateward cannot read (\`if (result.error && isApiError(result.error))\`) is listed as a place not checked. Test it in one of the ways below, then narrow further inside. A test reads the names the result's type gives its parts: \`error\`, a trigger's \`data\`, a Result's \`ok\` or \`success\`, and the \`isOk()\` and \`isErr()\` methods. Another name (\`isError\`, \`isSuccess\`, \`value\`, a function such as \`isFailure(result)\`) says nothing by itself: list it in \`failureNames\` or \`successNames\`, and the test is read.
|
|
48
52
|
|
|
49
53
|
## What it does not catch
|
|
50
54
|
|
|
@@ -54,45 +58,63 @@ It looks at a call whose value is data or an error: a promise with an \`unwrap()
|
|
|
54
58
|
- it is awaited as a statement inside a \`try\` after another call (an optimistic \`setFolders(…)\`), with more lines after it: when it fails, those lines run and the \`catch\` (the rollback) does not;
|
|
55
59
|
- a trigger is awaited as a statement outside a \`try\`, with more lines after it (\`await sendReply(x); setText("")\`);
|
|
56
60
|
- it is stored, then its data is read before it is checked;
|
|
57
|
-
- it is stored, and its error is read in an \`if\` that does not \`return\` or \`throw\` (\`"error" in result\`, \`result.error\`, \`!result.ok\`, or an \`error\`
|
|
61
|
+
- it is stored, and its error is read in an \`if\` that does not \`return\` or \`throw\` (\`"error" in result\`, \`result.error\`, \`!result.ok\`, or an \`error\` taken out of it), with more lines after that \`if\`.
|
|
58
62
|
|
|
59
63
|
It is silent on:
|
|
60
64
|
|
|
61
65
|
- a Result dropped as a statement: that is \`errors/result-ignored\`;
|
|
62
66
|
- lines after the call that only set back a pending state set before it (\`setSaving(true)\` … \`setSaving(false)\`): they run either way on purpose;
|
|
63
67
|
- a \`try\` with another \`await\` or a \`throw\` in it: the \`catch\` may be there for that;
|
|
68
|
+
- an \`if\` whose failure branch ends in a call declared to return \`never\` (\`process.exit(1)\`): the lines after it do not run;
|
|
64
69
|
- a result passed on, returned, stored elsewhere, or checked in a callback;
|
|
65
70
|
- a promise that rejects on failure (react-query's \`mutateAsync\`, \`fetch\`): it has no \`unwrap()\` that resolves to data or an error.
|
|
66
71
|
|
|
67
72
|
## Getting the best from it
|
|
68
73
|
|
|
69
|
-
Code that says what it means is left alone: \`void trigger(…)\`, \`.unwrap()\`, a check (\`"error" in result\`, \`if (result.error) return\`, \`
|
|
74
|
+
Code that says what it means is left alone: \`void trigger(…)\`, \`.unwrap()\`, a check (\`"error" in result\`, \`if (result.error) return\`, \`result.isErr()\`, \`const { data, error } = await dispatch(…); if (error) throw …\`) before the success path, an \`if\` with an \`else\` for the success path, and a component that reads the trigger's own \`error\` from its hook (\`const [save, { error }] = useSaveMutation()\`), or a name \`failureNames\` lists (\`isError\`).
|
|
70
75
|
|
|
71
76
|
## Turn it on or off
|
|
72
77
|
|
|
78
|
+
${offByDefaultText(OFF_BY_DEFAULT)}
|
|
79
|
+
|
|
73
80
|
\`\`\`ts
|
|
74
|
-
|
|
81
|
+
addons: ["errors/result-unchecked"]
|
|
82
|
+
rules: { "errors/result-unchecked": "error" } // on, as an error
|
|
83
|
+
rules: { "errors/result-unchecked": ["warning", { failureNames: ["isError"], successNames: ["isSuccess"] }] } // RTK Query's state flags
|
|
75
84
|
\`\`\`
|
|
76
85
|
`;
|
|
86
|
+
const OPTIONS = {
|
|
87
|
+
failureNames: option.strings({
|
|
88
|
+
default: [],
|
|
89
|
+
description: "Names (or globs like isErr*) that are true when the call failed, besides the result's own `error`: a property of the result (`isError`), or a function called with it (`isFailure(result)`). Its type does not say what such a name means.",
|
|
90
|
+
}),
|
|
91
|
+
successNames: option.strings({
|
|
92
|
+
default: [],
|
|
93
|
+
description: "Names (or globs) that are true when the call worked, besides the result's own `data`, `ok` and `success`: a property of the result (`isSuccess`, `value`), or a function called with it (`isOk(result)`).",
|
|
94
|
+
}),
|
|
95
|
+
};
|
|
77
96
|
/** The longest call an example line shows before its arguments become `…`. */
|
|
78
97
|
const CALL_MAX = 60;
|
|
79
98
|
/** The longest condition the fix hint quotes. */
|
|
80
99
|
const CONDITION_MAX = 50;
|
|
81
|
-
//
|
|
82
|
-
//
|
|
100
|
+
// The names the result's shape gives its parts (`error`, a trigger's `data`, a Result's `ok` or
|
|
101
|
+
// `success`): what testing one says is in the type. Any other name is read through the options.
|
|
83
102
|
const ALIAS_KINDS = new Map([
|
|
84
103
|
["error", "error"],
|
|
85
|
-
["isError", "error"],
|
|
86
104
|
["data", "data"],
|
|
87
|
-
["value", "data"],
|
|
88
105
|
["ok", "ok"],
|
|
89
106
|
["success", "ok"],
|
|
90
|
-
["isSuccess", "ok"],
|
|
91
107
|
]);
|
|
92
|
-
const DATA_PROPERTIES = new Set(["data"
|
|
93
|
-
const SUCCESS_PROPERTIES = new Set(["data", "
|
|
94
|
-
|
|
95
|
-
|
|
108
|
+
const DATA_PROPERTIES = new Set(["data"]);
|
|
109
|
+
const SUCCESS_PROPERTIES = new Set(["data", "ok", "success"]);
|
|
110
|
+
/** What a name the options list says: `failure`, `success`, or nothing. */
|
|
111
|
+
function namedPolarity(name, names) {
|
|
112
|
+
if (matchesName(name, names.failure))
|
|
113
|
+
return "failure";
|
|
114
|
+
if (matchesName(name, names.success))
|
|
115
|
+
return "success";
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
96
118
|
function strip(expression) {
|
|
97
119
|
return ts.isParenthesizedExpression(expression) ? strip(expression.expression) : expression;
|
|
98
120
|
}
|
|
@@ -120,27 +142,89 @@ function callText(call, ctx) {
|
|
|
120
142
|
? `${shorten(call.expression.getText(ctx.sourceFile), CALL_MAX)}(…)`
|
|
121
143
|
: whole;
|
|
122
144
|
}
|
|
123
|
-
/**
|
|
124
|
-
function
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
145
|
+
/** Whether the function returns a value anywhere in its own body (not in a nested function). */
|
|
146
|
+
function returnsValue(body) {
|
|
147
|
+
return inBody(body, (one) => ts.isReturnStatement(one) && one.expression !== undefined);
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* How the code stops where `node` is: inside a `try` with a `catch` it throws (a `return` would
|
|
151
|
+
* skip the `catch` and its rollback); in a function that returns nothing it returns; otherwise
|
|
152
|
+
* what to return depends on the function, which the example leaves to its writer.
|
|
153
|
+
*/
|
|
154
|
+
function exitOf(node, ctx) {
|
|
155
|
+
for (let child = node; !ts.isSourceFile(child); child = child.parent) {
|
|
156
|
+
if (isFunctionLike(child))
|
|
157
|
+
break;
|
|
158
|
+
const parent = child.parent;
|
|
159
|
+
if (ts.isTryStatement(parent) &&
|
|
160
|
+
parent.tryBlock === child &&
|
|
161
|
+
parent.catchClause !== undefined) {
|
|
162
|
+
return "throw";
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const fn = ts.findAncestor(node.parent, ts.isFunctionLike);
|
|
166
|
+
if (fn === undefined)
|
|
167
|
+
return "other";
|
|
168
|
+
if (fn.type !== undefined) {
|
|
169
|
+
const returnType = fn.type.getText(ctx.sourceFile).replace(/\s+/g, "");
|
|
170
|
+
return returnType === "void" || returnType === "Promise<void>" ? "return" : "other";
|
|
171
|
+
}
|
|
172
|
+
const body = ts.isFunctionDeclaration(fn) ||
|
|
173
|
+
ts.isFunctionExpression(fn) ||
|
|
174
|
+
ts.isArrowFunction(fn) ||
|
|
175
|
+
ts.isMethodDeclaration(fn)
|
|
176
|
+
? fn.body
|
|
177
|
+
: undefined;
|
|
178
|
+
return body !== undefined && ts.isBlock(body) && !returnsValue(body) ? "return" : "other";
|
|
179
|
+
}
|
|
180
|
+
/** What ends the branch that handles a failure, as one statement, or `{ … }` when it cannot be written. */
|
|
181
|
+
function stopStatement(exit, error) {
|
|
182
|
+
if (exit === "return")
|
|
183
|
+
return "return;";
|
|
184
|
+
return exit === "throw" && error !== undefined ? `throw ${error};` : "{ … }";
|
|
185
|
+
}
|
|
186
|
+
/** The condition that is true when the call failed, in the result's own shape and names, and the error it holds. */
|
|
187
|
+
function failureTest(tracked) {
|
|
188
|
+
const errorAlias = tracked.errorName ?? [...tracked.aliases].find(([, kind]) => kind === "error")?.[0];
|
|
189
|
+
if (tracked.whole === undefined && errorAlias !== undefined) {
|
|
190
|
+
return { test: errorAlias, error: tracked.errorName };
|
|
191
|
+
}
|
|
128
192
|
const name = tracked.whole ?? "result";
|
|
129
193
|
switch (tracked.kind) {
|
|
130
194
|
case "trigger":
|
|
131
|
-
return `
|
|
195
|
+
return { test: `"error" in ${name}`, error: `${name}.error` };
|
|
132
196
|
case "ok":
|
|
133
|
-
return
|
|
197
|
+
return { test: `!${name}.ok`, error: `${name}.error` };
|
|
134
198
|
case "success":
|
|
135
|
-
return
|
|
199
|
+
return { test: `!${name}.success`, error: `${name}.error` };
|
|
136
200
|
case "isErr":
|
|
137
|
-
return
|
|
201
|
+
return { test: `${name}.isErr()`, error: undefined };
|
|
138
202
|
default: {
|
|
139
203
|
const unreachable = tracked.kind;
|
|
140
204
|
return unreachable;
|
|
141
205
|
}
|
|
142
206
|
}
|
|
143
207
|
}
|
|
208
|
+
/** The line that stops when the call failed, in the result's own shape and names. */
|
|
209
|
+
function checkLine(tracked, exit) {
|
|
210
|
+
const { test, error } = failureTest(tracked);
|
|
211
|
+
return `if (${test}) ${stopStatement(exit, error)}`;
|
|
212
|
+
}
|
|
213
|
+
/** The sentence that says what the check does when the call failed. */
|
|
214
|
+
function stopsWith(exit) {
|
|
215
|
+
switch (exit) {
|
|
216
|
+
case "return":
|
|
217
|
+
return "return when it failed";
|
|
218
|
+
case "throw":
|
|
219
|
+
return "throw its error when it failed, so the `catch` runs";
|
|
220
|
+
case "other":
|
|
221
|
+
return "stop when it failed (return what the function returns, or throw)";
|
|
222
|
+
default: {
|
|
223
|
+
const unreachable = exit;
|
|
224
|
+
return unreachable;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
144
228
|
/** Whether an identifier is a name read as a value (not `x.name`, not a property's key). */
|
|
145
229
|
function isValueName(node) {
|
|
146
230
|
const parent = node.parent;
|
|
@@ -263,6 +347,8 @@ function polarity(expression, tracked) {
|
|
|
263
347
|
const alias = tracked.aliases.get(code.text);
|
|
264
348
|
if (alias === "error")
|
|
265
349
|
return "failure";
|
|
350
|
+
if (alias === "unknown")
|
|
351
|
+
return "undecided";
|
|
266
352
|
if (alias !== undefined)
|
|
267
353
|
return "success";
|
|
268
354
|
return code.text === tracked.whole ? "undecided" : "none";
|
|
@@ -270,7 +356,9 @@ function polarity(expression, tracked) {
|
|
|
270
356
|
if (ts.isPropertyAccessExpression(code) && isWhole(code.expression, tracked)) {
|
|
271
357
|
if (code.name.text === "error")
|
|
272
358
|
return "failure";
|
|
273
|
-
|
|
359
|
+
if (SUCCESS_PROPERTIES.has(code.name.text))
|
|
360
|
+
return "success";
|
|
361
|
+
return namedPolarity(code.name.text, tracked.names) ?? "undecided";
|
|
274
362
|
}
|
|
275
363
|
if (ts.isCallExpression(code)) {
|
|
276
364
|
const callee = strip(code.expression);
|
|
@@ -285,10 +373,9 @@ function polarity(expression, tracked) {
|
|
|
285
373
|
code.arguments.length === 1 &&
|
|
286
374
|
argument !== undefined &&
|
|
287
375
|
isWhole(argument, tracked)) {
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
return "success";
|
|
376
|
+
const named = namedPolarity(callee.text, tracked.names);
|
|
377
|
+
if (named !== undefined)
|
|
378
|
+
return named;
|
|
292
379
|
}
|
|
293
380
|
}
|
|
294
381
|
if (ts.isBinaryExpression(code)) {
|
|
@@ -298,30 +385,44 @@ function polarity(expression, tracked) {
|
|
|
298
385
|
isWhole(code.right, tracked)) {
|
|
299
386
|
if (code.left.text === "error")
|
|
300
387
|
return "failure";
|
|
301
|
-
|
|
388
|
+
if (DATA_PROPERTIES.has(code.left.text))
|
|
389
|
+
return "success";
|
|
390
|
+
return namedPolarity(code.left.text, tracked.names) ?? "undecided";
|
|
302
391
|
}
|
|
303
392
|
if (EQUAL.has(operator) || NOT_EQUAL.has(operator))
|
|
304
393
|
return comparedPolarity(code, tracked);
|
|
305
394
|
}
|
|
306
395
|
return mentions(code, tracked) ? "undecided" : "none";
|
|
307
396
|
}
|
|
308
|
-
/**
|
|
309
|
-
|
|
397
|
+
/**
|
|
398
|
+
* Whether a statement always leaves the block it is in: `return`, `throw`, `break`, `continue`,
|
|
399
|
+
* or a call whose declared return type is `never` (`process.exit(1)`), read from its type.
|
|
400
|
+
*/
|
|
401
|
+
function exits(statement, ctx) {
|
|
310
402
|
if (ts.isReturnStatement(statement) ||
|
|
311
403
|
ts.isThrowStatement(statement) ||
|
|
312
404
|
ts.isBreakStatement(statement) ||
|
|
313
405
|
ts.isContinueStatement(statement)) {
|
|
314
406
|
return true;
|
|
315
407
|
}
|
|
408
|
+
if (ts.isExpressionStatement(statement))
|
|
409
|
+
return callsNever(statement.expression, ctx);
|
|
316
410
|
if (ts.isBlock(statement))
|
|
317
|
-
return statement.statements.some(exits);
|
|
411
|
+
return statement.statements.some((one) => exits(one, ctx));
|
|
318
412
|
if (ts.isIfStatement(statement)) {
|
|
319
|
-
return (exits(statement.thenStatement) &&
|
|
413
|
+
return (exits(statement.thenStatement, ctx) &&
|
|
320
414
|
statement.elseStatement !== undefined &&
|
|
321
|
-
exits(statement.elseStatement));
|
|
415
|
+
exits(statement.elseStatement, ctx));
|
|
322
416
|
}
|
|
323
417
|
return false;
|
|
324
418
|
}
|
|
419
|
+
/** A call, awaited or not, whose type is `never`: it does not return to the next line. */
|
|
420
|
+
function callsNever(expression, ctx) {
|
|
421
|
+
let inner = strip(expression);
|
|
422
|
+
while (ts.isAwaitExpression(inner))
|
|
423
|
+
inner = strip(inner.expression);
|
|
424
|
+
return ts.isCallExpression(inner) && ctx.types.builtinTypeOf(inner, "as-is") === "never";
|
|
425
|
+
}
|
|
325
426
|
function isFunctionLike(node) {
|
|
326
427
|
return ts.isFunctionLike(node) || ts.isClassLike(node);
|
|
327
428
|
}
|
|
@@ -332,15 +433,18 @@ function inBody(node, test) {
|
|
|
332
433
|
return ts.forEachChild(node, (child) => !isFunctionLike(child) && inBody(child, test)) === true;
|
|
333
434
|
}
|
|
334
435
|
/**
|
|
335
|
-
*
|
|
336
|
-
*
|
|
337
|
-
*
|
|
436
|
+
* What the component reads of the trigger's own state from its hook: `const [save, { error }] =
|
|
437
|
+
* useSaveMutation()`, or `const [save, saving] = …` and `saving.error` read. `reads`: it reads the
|
|
438
|
+
* failure (the result's `error`, or a name `failureNames` lists), so failure is handled through the
|
|
439
|
+
* hook's result (stated intent) and code after the call may run either way. `unread`: it reads the
|
|
440
|
+
* state only by names nothing states (`isError`). `none`: it does not read it.
|
|
338
441
|
*/
|
|
339
|
-
function
|
|
442
|
+
function hookState(call, ctx) {
|
|
340
443
|
const callee = strip(call.expression);
|
|
341
444
|
if (!ts.isIdentifier(callee))
|
|
342
|
-
return
|
|
343
|
-
|
|
445
|
+
return "none";
|
|
446
|
+
// The result's own `error`, and the names the `failureNames` option gives.
|
|
447
|
+
const reads = (name) => name === "error" || matchesName(name, ctx.options.failureNames);
|
|
344
448
|
const hook = findNode(ctx.sourceFile, (node) => {
|
|
345
449
|
if (!ts.isVariableDeclaration(node) || !ts.isArrayBindingPattern(node.name))
|
|
346
450
|
return false;
|
|
@@ -351,26 +455,51 @@ function hookStateRead(call, ctx) {
|
|
|
351
455
|
trigger.name.text === callee.text);
|
|
352
456
|
});
|
|
353
457
|
if (hook === undefined || !ts.isVariableDeclaration(hook))
|
|
354
|
-
return
|
|
458
|
+
return "none";
|
|
355
459
|
if (!ts.isArrayBindingPattern(hook.name))
|
|
356
|
-
return
|
|
460
|
+
return "none";
|
|
357
461
|
const second = hook.name.elements[1];
|
|
358
462
|
if (second === undefined || !ts.isBindingElement(second))
|
|
359
|
-
return
|
|
463
|
+
return "none";
|
|
360
464
|
const found = second.name;
|
|
465
|
+
const names = [];
|
|
361
466
|
if (ts.isObjectBindingPattern(found)) {
|
|
362
|
-
|
|
467
|
+
for (const element of found.elements) {
|
|
363
468
|
const key = element.propertyName ?? element.name;
|
|
364
|
-
|
|
469
|
+
if (ts.isIdentifier(key))
|
|
470
|
+
names.push(key.text);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
else if (ts.isIdentifier(found)) {
|
|
474
|
+
const name = found.text;
|
|
475
|
+
someNode(ctx.sourceFile, (node) => {
|
|
476
|
+
if (ts.isPropertyAccessExpression(node) &&
|
|
477
|
+
ts.isIdentifier(node.expression) &&
|
|
478
|
+
node.expression.text === name) {
|
|
479
|
+
names.push(node.name.text);
|
|
480
|
+
}
|
|
481
|
+
return false;
|
|
365
482
|
});
|
|
366
483
|
}
|
|
367
|
-
if (
|
|
368
|
-
return
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
484
|
+
if (names.some(reads))
|
|
485
|
+
return "reads";
|
|
486
|
+
return names.length > 0 ? "unread" : "none";
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Whether the component handles the trigger's failure through its hook, so nothing is reported:
|
|
490
|
+
* it reads it, or it reads the hook's state by names nothing states, and the call is "not
|
|
491
|
+
* checked" at `node`.
|
|
492
|
+
*/
|
|
493
|
+
function handledByHook(call, node, ctx) {
|
|
494
|
+
const state = hookState(call, ctx);
|
|
495
|
+
if (state === "unread") {
|
|
496
|
+
ctx.unknown({
|
|
497
|
+
node,
|
|
498
|
+
message: `not checked: whether the component shows the failure of \`${calleeText(call, ctx)}(…)\` from its hook: no name it reads says so`,
|
|
499
|
+
hint: "list the name that is true when the call failed (`isError`) in the rule's `failureNames` option",
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
return state !== "none";
|
|
374
503
|
}
|
|
375
504
|
/** `await call(…);` as a statement: the call, or undefined. */
|
|
376
505
|
function droppedAwait(statement) {
|
|
@@ -420,18 +549,12 @@ function checkTry(statement, ctx) {
|
|
|
420
549
|
const after = statements.slice(index + 1);
|
|
421
550
|
if (after.every((next) => undoesPending(next, statements.slice(0, index))))
|
|
422
551
|
continue;
|
|
423
|
-
if (
|
|
552
|
+
if (handledByHook(call, inner, ctx))
|
|
424
553
|
continue;
|
|
425
554
|
ctx.report({
|
|
426
555
|
node: inner,
|
|
427
556
|
message: `code after the call runs even when \`${calleeText(call, ctx)}(…)\` failed, and the \`catch\` does not`,
|
|
428
|
-
hint:
|
|
429
|
-
'add `.unwrap()` so a failure reaches the `catch` (quick fix), or check `"error" in result` and return:',
|
|
430
|
-
example([
|
|
431
|
-
`const result = await ${callText(call, ctx)};`,
|
|
432
|
-
`if ("error" in result) return;`,
|
|
433
|
-
]),
|
|
434
|
-
].join("\n"),
|
|
557
|
+
hint: triggerHint(inner, call, "catch", ctx),
|
|
435
558
|
fixes: [unwrapFix(call, "Add `.unwrap()` so a failure reaches the `catch`", ctx)],
|
|
436
559
|
});
|
|
437
560
|
}
|
|
@@ -442,14 +565,35 @@ function checkTry(statement, ctx) {
|
|
|
442
565
|
// The statement, as `errors/result-ignored` reports it, so that rule can yield to this one.
|
|
443
566
|
node: inner,
|
|
444
567
|
message: `\`catch\` never runs for \`${calleeText(call, ctx)}(…)\`: it does not throw when it fails`,
|
|
445
|
-
hint:
|
|
446
|
-
'add `.unwrap()` (quick fix), or check `"error" in result` and return, so the code after it does not run on failure:',
|
|
447
|
-
example([`const result = await ${callText(call, ctx)};`, `if ("error" in result) return;`]),
|
|
448
|
-
].join("\n"),
|
|
568
|
+
hint: triggerHint(inner, call, "catch", ctx),
|
|
449
569
|
fixes: [unwrapFix(call, "Add `.unwrap()` so a failure reaches the `catch`", ctx)],
|
|
450
570
|
});
|
|
451
571
|
}
|
|
452
572
|
}
|
|
573
|
+
/** The three readings of a trigger whose failure is not checked: stop, throw it, or go on on purpose. */
|
|
574
|
+
function triggerHint(statement, call, where, ctx) {
|
|
575
|
+
const fn = ts.findAncestor(statement.parent, ts.isFunctionLike);
|
|
576
|
+
const name = freeName(fn ?? ctx.sourceFile, ctx.sourceFile, ["result", "outcome", "response"]);
|
|
577
|
+
const stored = `const ${name} = await ${callText(call, ctx)};`;
|
|
578
|
+
const stop = stopStatement(where === "catch" ? "throw" : exitOf(statement, ctx), `${name}.error`);
|
|
579
|
+
const ways = where === "catch"
|
|
580
|
+
? [
|
|
581
|
+
"- add `.unwrap()` so a failure throws into the `catch` (quick fix)",
|
|
582
|
+
"- or check the result and throw its error into the `catch`",
|
|
583
|
+
example([stored, `if ("error" in ${name}) ${stop}`]),
|
|
584
|
+
]
|
|
585
|
+
: [
|
|
586
|
+
"- add `.unwrap()` so a failure throws (quick fix), and put the call in a `try` with a `catch`: nothing else catches it",
|
|
587
|
+
"- or check the result, and stop there",
|
|
588
|
+
example([stored, `if ("error" in ${name}) ${stop}`]),
|
|
589
|
+
];
|
|
590
|
+
return [
|
|
591
|
+
"one of",
|
|
592
|
+
...ways,
|
|
593
|
+
"- or, if the lines after it should run either way, say so with an `else` for the success path",
|
|
594
|
+
example([`if ("error" in ${name}) { … } else { … }`]),
|
|
595
|
+
].join("\n");
|
|
596
|
+
}
|
|
453
597
|
function unwrapFix(call, title, ctx) {
|
|
454
598
|
const at = call.getEnd();
|
|
455
599
|
return {
|
|
@@ -523,38 +667,53 @@ function checkDropped(statement, ctx) {
|
|
|
523
667
|
// The type questions after the syntax that rules most statements out.
|
|
524
668
|
if (after.every((next) => undoesPending(next, before)))
|
|
525
669
|
return;
|
|
526
|
-
if (kindOf(call, true, ctx) !== "trigger" ||
|
|
670
|
+
if (kindOf(call, true, ctx) !== "trigger" || handledByHook(call, statement, ctx))
|
|
527
671
|
return;
|
|
528
672
|
ctx.report({
|
|
529
673
|
node: statement,
|
|
530
674
|
message: `code after the call runs even when \`${calleeText(call, ctx)}(…)\` failed`,
|
|
531
|
-
hint:
|
|
532
|
-
'add `.unwrap()` so a failure throws (quick fix), or check `"error" in result` and return:',
|
|
533
|
-
example([`const result = await ${callText(call, ctx)};`, `if ("error" in result) return;`]),
|
|
534
|
-
].join("\n"),
|
|
675
|
+
hint: triggerHint(statement, call, "outside", ctx),
|
|
535
676
|
fixes: [unwrapFix(call, "Add `.unwrap()` so a failure stops the function", ctx)],
|
|
536
677
|
});
|
|
537
678
|
}
|
|
538
679
|
/** What a stored result is reached by: `const r = …` or `const { data, error } = …`. */
|
|
539
680
|
function trackedOf(declaration, call, kind, ctx) {
|
|
540
681
|
const callee = calleeText(call, ctx);
|
|
682
|
+
const names = { failure: ctx.options.failureNames, success: ctx.options.successNames };
|
|
541
683
|
if (ts.isIdentifier(declaration.name)) {
|
|
542
|
-
return { whole: declaration.name.text, aliases: new Map(), callee, kind };
|
|
684
|
+
return { whole: declaration.name.text, aliases: new Map(), callee, kind, names };
|
|
543
685
|
}
|
|
544
686
|
if (!ts.isObjectBindingPattern(declaration.name))
|
|
545
687
|
return undefined;
|
|
546
688
|
const aliases = new Map();
|
|
689
|
+
let errorName;
|
|
690
|
+
let known = false;
|
|
547
691
|
for (const element of declaration.name.elements) {
|
|
548
692
|
if (element.dotDotDotToken !== undefined || !ts.isIdentifier(element.name))
|
|
549
693
|
return undefined;
|
|
550
694
|
const key = element.propertyName ?? element.name;
|
|
551
695
|
if (!ts.isIdentifier(key))
|
|
552
696
|
return undefined;
|
|
553
|
-
const
|
|
554
|
-
|
|
555
|
-
|
|
697
|
+
const named = namedPolarity(key.text, names);
|
|
698
|
+
const alias = ALIAS_KINDS.get(key.text) ??
|
|
699
|
+
(named === "failure" ? "error" : named === "success" ? "ok" : "unknown");
|
|
700
|
+
if (alias !== "unknown")
|
|
701
|
+
known = true;
|
|
702
|
+
aliases.set(element.name.text, alias);
|
|
703
|
+
if (key.text === "error")
|
|
704
|
+
errorName = element.name.text;
|
|
556
705
|
}
|
|
557
|
-
return
|
|
706
|
+
return !known
|
|
707
|
+
? undefined
|
|
708
|
+
: {
|
|
709
|
+
whole: undefined,
|
|
710
|
+
aliases,
|
|
711
|
+
...(errorName === undefined ? {} : { errorName }),
|
|
712
|
+
pattern: declaration.name.getText(),
|
|
713
|
+
callee,
|
|
714
|
+
kind,
|
|
715
|
+
names,
|
|
716
|
+
};
|
|
558
717
|
}
|
|
559
718
|
function goesOnHeadline(tracked, after) {
|
|
560
719
|
const what = after === "if" ? "the `if`" : "the call";
|
|
@@ -603,7 +762,7 @@ function returnsResult(statement, tracked) {
|
|
|
603
762
|
* Case (b), read from syntax alone: the statements after a stored result, until it is checked,
|
|
604
763
|
* passed on or read. `tracked.kind` matters only to `readsData` (a trigger's data).
|
|
605
764
|
*/
|
|
606
|
-
function storedOutcome(rest, tracked) {
|
|
765
|
+
function storedOutcome(rest, tracked, ctx) {
|
|
607
766
|
for (const [index, next] of rest.entries()) {
|
|
608
767
|
if (ts.isIfStatement(next)) {
|
|
609
768
|
const test = polarity(next.expression, tracked);
|
|
@@ -612,7 +771,7 @@ function storedOutcome(rest, tracked) {
|
|
|
612
771
|
if (test !== "none") {
|
|
613
772
|
const failed = test === "failure" ? next.thenStatement : next.elseStatement;
|
|
614
773
|
const worked = test === "failure" ? next.elseStatement : next.thenStatement;
|
|
615
|
-
if (failed === undefined || worked !== undefined || exits(failed))
|
|
774
|
+
if (failed === undefined || worked !== undefined || exits(failed, ctx))
|
|
616
775
|
return { kind: "none" };
|
|
617
776
|
const later = rest.slice(index + 1);
|
|
618
777
|
return {
|
|
@@ -626,14 +785,58 @@ function storedOutcome(rest, tracked) {
|
|
|
626
785
|
return { kind: "none" };
|
|
627
786
|
if (readsData(next, tracked))
|
|
628
787
|
return { kind: "reads-data" };
|
|
629
|
-
if (mentions(next, tracked) || exits(next))
|
|
788
|
+
if (mentions(next, tracked) || exits(next, ctx))
|
|
630
789
|
return { kind: "none" };
|
|
631
790
|
}
|
|
632
791
|
return { kind: "none" };
|
|
633
792
|
}
|
|
793
|
+
/** Whether `error` of the whole result can be read inside the branch of `test`: the test narrows the result. */
|
|
794
|
+
function narrowsWhole(test, tracked) {
|
|
795
|
+
const code = strip(test);
|
|
796
|
+
if (ts.isPrefixUnaryExpression(code) && code.operator === ts.SyntaxKind.ExclamationToken) {
|
|
797
|
+
return narrowsWhole(code.operand, tracked);
|
|
798
|
+
}
|
|
799
|
+
if (ts.isBinaryExpression(code)) {
|
|
800
|
+
const operator = code.operatorToken.kind;
|
|
801
|
+
if (operator === ts.SyntaxKind.InKeyword)
|
|
802
|
+
return true;
|
|
803
|
+
if (operator === ts.SyntaxKind.AmpersandAmpersandToken)
|
|
804
|
+
return narrowsWhole(code.left, tracked);
|
|
805
|
+
return false;
|
|
806
|
+
}
|
|
807
|
+
return ts.isPropertyAccessExpression(code) && isWhole(code.expression, tracked);
|
|
808
|
+
}
|
|
809
|
+
/** The two readings of an `if` that reads the failure and goes on: end the branch, or say the lines run either way. */
|
|
810
|
+
function goesOnHint(test, tracked, ctx) {
|
|
811
|
+
const exit = exitOf(test, ctx);
|
|
812
|
+
const condition = shorten(test.getText(ctx.sourceFile), CONDITION_MAX);
|
|
813
|
+
const error = tracked.whole === undefined
|
|
814
|
+
? tracked.errorName
|
|
815
|
+
: narrowsWhole(test, tracked)
|
|
816
|
+
? `${tracked.whole}.error`
|
|
817
|
+
: undefined;
|
|
818
|
+
const stop = stopStatement(exit, error);
|
|
819
|
+
const how = exit === "return"
|
|
820
|
+
? "with `return`"
|
|
821
|
+
: exit === "throw"
|
|
822
|
+
? "by throwing its error, so the `catch` and its rollback run"
|
|
823
|
+
: "with a `return` of what the function returns, or a `throw`";
|
|
824
|
+
return [
|
|
825
|
+
"one of",
|
|
826
|
+
`- end the branch that handles the failure ${how}`,
|
|
827
|
+
example([
|
|
828
|
+
`if (${condition}) {`,
|
|
829
|
+
" // … what it shows now",
|
|
830
|
+
...(stop === "{ … }" ? [] : [` ${stop}`]),
|
|
831
|
+
"}",
|
|
832
|
+
]),
|
|
833
|
+
"- or, if the lines after the `if` should run either way, say so with an `else` for the success path",
|
|
834
|
+
example([`if (${condition}) { … } else { … }`]),
|
|
835
|
+
].join("\n");
|
|
836
|
+
}
|
|
634
837
|
/** Case (b): reports what `storedOutcome` found. */
|
|
635
838
|
function followStored(statement, before, rest, tracked, call, ctx) {
|
|
636
|
-
const outcome = storedOutcome(rest, tracked);
|
|
839
|
+
const outcome = storedOutcome(rest, tracked, ctx);
|
|
637
840
|
switch (outcome.kind) {
|
|
638
841
|
case "none":
|
|
639
842
|
return;
|
|
@@ -641,40 +844,58 @@ function followStored(statement, before, rest, tracked, call, ctx) {
|
|
|
641
844
|
ctx.unknown({
|
|
642
845
|
node: outcome.test,
|
|
643
846
|
message: `not checked: whether the \`if\` tests that \`${tracked.callee}(…)\` failed: it does not test the result itself`,
|
|
644
|
-
hint:
|
|
847
|
+
hint: [
|
|
848
|
+
"one of",
|
|
849
|
+
`- test the result itself, as in \`${checkLine(tracked, exitOf(outcome.test, ctx))}\`, so the check can be followed`,
|
|
850
|
+
"- or, if a name the `if` tests says the call failed or worked (`isError`, `isFailure(result)`), list it in the rule's `failureNames` or `successNames` option",
|
|
851
|
+
].join("\n"),
|
|
645
852
|
});
|
|
646
853
|
return;
|
|
647
854
|
case "goes-on": {
|
|
648
|
-
if (outcome.after.every((one) => undoesPending(one, before)) ||
|
|
855
|
+
if (outcome.after.every((one) => undoesPending(one, before)) ||
|
|
856
|
+
handledByHook(call, outcome.test, ctx)) {
|
|
649
857
|
return;
|
|
650
858
|
}
|
|
651
859
|
ctx.report({
|
|
652
860
|
node: outcome.test,
|
|
653
861
|
message: goesOnHeadline(tracked, "if"),
|
|
654
|
-
hint:
|
|
655
|
-
"end the branch that handles the failure with `return` (or `throw`):",
|
|
656
|
-
example([
|
|
657
|
-
`if (${shorten(outcome.test.getText(ctx.sourceFile), CONDITION_MAX)}) {`,
|
|
658
|
-
" // … what it shows now",
|
|
659
|
-
" return;",
|
|
660
|
-
"}",
|
|
661
|
-
]),
|
|
662
|
-
].join("\n"),
|
|
862
|
+
hint: goesOnHint(outcome.test, tracked, ctx),
|
|
663
863
|
});
|
|
664
864
|
return;
|
|
665
865
|
}
|
|
666
866
|
case "reads-data": {
|
|
667
|
-
if (
|
|
867
|
+
if (handledByHook(call, statement, ctx))
|
|
668
868
|
return;
|
|
669
869
|
const data = tracked.whole === undefined
|
|
670
870
|
? ([...tracked.aliases].find(([, kind]) => kind === "data")?.[0] ?? "data")
|
|
671
871
|
: `${tracked.whole}.data`;
|
|
872
|
+
const exit = exitOf(statement, ctx);
|
|
873
|
+
const hasError = tracked.whole !== undefined ||
|
|
874
|
+
[...tracked.aliases.values()].some((kind) => kind === "error");
|
|
875
|
+
if (hasError) {
|
|
876
|
+
ctx.report({
|
|
877
|
+
node: statement,
|
|
878
|
+
message: goesOnHeadline(tracked, "statement"),
|
|
879
|
+
hint: [
|
|
880
|
+
`check that it worked before reading \`${data}\`, and ${stopsWith(exit)}:`,
|
|
881
|
+
example([checkLine(tracked, exit)]),
|
|
882
|
+
].join("\n"),
|
|
883
|
+
});
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
// Only `data` was taken out: there is nothing to test, so the whole result is kept first.
|
|
887
|
+
const name = freeName(ts.findAncestor(statement.parent, ts.isFunctionLike) ?? ctx.sourceFile, ctx.sourceFile, ["result", "outcome", "response"]);
|
|
888
|
+
const pattern = tracked.pattern === undefined ? "{ data }" : codeOnOneLine(tracked.pattern);
|
|
672
889
|
ctx.report({
|
|
673
890
|
node: statement,
|
|
674
891
|
message: goesOnHeadline(tracked, "statement"),
|
|
675
892
|
hint: [
|
|
676
|
-
`check
|
|
677
|
-
example([
|
|
893
|
+
`keep the whole result and check it before reading \`${data}\`, and ${stopsWith(exit)}:`,
|
|
894
|
+
example([
|
|
895
|
+
`const ${name} = await ${callText(call, ctx)};`,
|
|
896
|
+
checkLine({ ...tracked, whole: name }, exit),
|
|
897
|
+
`const ${pattern} = ${name};`,
|
|
898
|
+
]),
|
|
678
899
|
].join("\n"),
|
|
679
900
|
});
|
|
680
901
|
return;
|
|
@@ -706,7 +927,7 @@ function checkDeclaration(statement, ctx) {
|
|
|
706
927
|
// before any test, and then nothing is said whatever they give. The kind matters only to a
|
|
707
928
|
// trigger's data, which only an awaited call can be; a trigger read finds the most.
|
|
708
929
|
const probe = trackedOf(declaration, call, awaited ? "trigger" : "ok", ctx);
|
|
709
|
-
if (probe === undefined || storedOutcome(rest, probe).kind === "none")
|
|
930
|
+
if (probe === undefined || storedOutcome(rest, probe, ctx).kind === "none")
|
|
710
931
|
return;
|
|
711
932
|
const kind = kindOf(call, awaited, ctx);
|
|
712
933
|
if (kind === undefined)
|
|
@@ -722,9 +943,12 @@ export const resultUnchecked = defineRule({
|
|
|
722
943
|
description: "A call that returns its failure instead of throwing never reaches the `catch`; without a check, the code after it runs as if the call worked.",
|
|
723
944
|
summary: "a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked",
|
|
724
945
|
defaultSeverity: "warning",
|
|
725
|
-
tier: "
|
|
946
|
+
tier: "addon",
|
|
947
|
+
addon: "result-unchecked",
|
|
948
|
+
offByDefault: OFF_BY_DEFAULT,
|
|
726
949
|
group: "callers",
|
|
727
950
|
heuristic: true,
|
|
951
|
+
options: OPTIONS,
|
|
728
952
|
explain: EXPLAIN,
|
|
729
953
|
},
|
|
730
954
|
check(ctx) {
|