@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.
Files changed (56) hide show
  1. package/README.md +9 -8
  2. package/dist/catch-hides-unexpected.d.ts +4 -1
  3. package/dist/catch-hides-unexpected.js +87 -11
  4. package/dist/catch-misses-error.d.ts +1 -1
  5. package/dist/catch-misses-error.js +63 -20
  6. package/dist/finally-can-throw.js +46 -6
  7. package/dist/index.d.ts +3 -1
  8. package/dist/index.js +1 -0
  9. package/dist/inference/analysis.d.ts +109 -0
  10. package/dist/inference/analysis.js +170 -0
  11. package/dist/inference/builtins.d.ts +7 -2
  12. package/dist/inference/builtins.js +20 -33
  13. package/dist/inference/deps.js +2 -2
  14. package/dist/inference/needs.d.ts +16 -0
  15. package/dist/inference/needs.js +27 -0
  16. package/dist/inference/packages.d.ts +24 -32
  17. package/dist/inference/packages.js +156 -675
  18. package/dist/inference/project.d.ts +2 -2
  19. package/dist/inference/project.js +3 -2
  20. package/dist/inference/solve.d.ts +29 -4
  21. package/dist/inference/solve.js +34 -5
  22. package/dist/inference/summarize.d.ts +28 -15
  23. package/dist/inference/summarize.js +339 -135
  24. package/dist/inference/summary.d.ts +46 -5
  25. package/dist/inference/summary.js +89 -13
  26. package/dist/inference/unreachable.d.ts +5 -0
  27. package/dist/inference/unreachable.js +160 -0
  28. package/dist/must-handle-error.d.ts +2 -1
  29. package/dist/must-handle-error.js +4 -4
  30. package/dist/narrow-try.d.ts +2 -0
  31. package/dist/narrow-try.js +62 -7
  32. package/dist/plugin.d.ts +12 -2
  33. package/dist/plugin.js +4 -2
  34. package/dist/react/fallbacks.js +35 -14
  35. package/dist/react/tree.d.ts +10 -0
  36. package/dist/react/tree.js +54 -7
  37. package/dist/refactors.js +35 -2
  38. package/dist/render-throw-without-boundary.d.ts +13 -4
  39. package/dist/render-throw-without-boundary.js +100 -10
  40. package/dist/result-ignored.d.ts +4 -1
  41. package/dist/result-ignored.js +51 -10
  42. package/dist/result-type.d.ts +2 -0
  43. package/dist/result-type.js +8 -2
  44. package/dist/result-unchecked.d.ts +4 -1
  45. package/dist/result-unchecked.js +320 -96
  46. package/dist/rules.meta.d.ts +29 -14
  47. package/dist/rules.meta.js +19 -14
  48. package/dist/syntax.d.ts +0 -13
  49. package/dist/syntax.js +0 -79
  50. package/dist/text.d.ts +15 -2
  51. package/dist/text.js +28 -5
  52. package/dist/throws-doc-mismatch.d.ts +1 -1
  53. package/dist/throws-doc-mismatch.js +59 -5
  54. package/dist/throws-reads.d.ts +3 -0
  55. package/dist/throws-reads.js +108 -0
  56. package/package.json +2 -2
package/dist/plugin.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { definePlugin, lazyRule, moduleLoader } from "@stateward/core";
2
2
  import { codeActions } from "./refactors.js";
3
3
  import { hover } from "./hover.js";
4
+ import { throws } from "./inference/analysis.js";
4
5
  import { libraryFacts } from "./inference/deps.js";
5
6
  import { inlayHints } from "./inlay.js";
6
7
  import { RULES } from "./rules.meta.js";
@@ -12,7 +13,6 @@ const load = {
12
13
  throwsDocMismatch: moduleLoader(() => import("./throws-doc-mismatch.js")),
13
14
  renderThrowWithoutBoundary: moduleLoader(() => import("./render-throw-without-boundary.js")),
14
15
  mustHandleError: moduleLoader(() => import("./must-handle-error.js")),
15
- narrowTry: moduleLoader(() => import("./narrow-try.js")),
16
16
  resultIgnored: moduleLoader(() => import("./result-ignored.js")),
17
17
  resultUnchecked: moduleLoader(() => import("./result-unchecked.js")),
18
18
  };
@@ -27,11 +27,13 @@ export function errors() {
27
27
  "throws-doc-mismatch": lazyRule(RULES["throws-doc-mismatch"], load.throwsDocMismatch, (module) => module.throwsDocMismatch),
28
28
  "render-throw-without-boundary": lazyRule(RULES["render-throw-without-boundary"], load.renderThrowWithoutBoundary, (module) => module.renderThrowWithoutBoundary),
29
29
  "must-handle-error": lazyRule(RULES["must-handle-error"], load.mustHandleError, (module) => module.mustHandleError),
30
- "narrow-try": lazyRule(RULES["narrow-try"], load.narrowTry, (module) => module.narrowTry),
31
30
  "result-ignored": lazyRule(RULES["result-ignored"], load.resultIgnored, (module) => module.resultIgnored),
32
31
  "result-unchecked": lazyRule(RULES["result-unchecked"], load.resultUnchecked, (module) => module.resultUnchecked),
33
32
  },
34
33
  editor: { hover, inlayHints, codeActions, libraryFacts },
34
+ analyses: { throws },
35
+ // Removed in R129: its precision followed the codebase's style (26% to 96%), not the rule.
36
+ removed: ["errors/narrow-try"],
35
37
  });
36
38
  }
37
39
  //# sourceMappingURL=plugin.js.map
@@ -1,13 +1,16 @@
1
1
  import { matchesName } from "@stateward/core";
2
2
  import { catchName, className } from "../inference/format.js";
3
3
  import { relation } from "../inference/solve.js";
4
- import { codeList, fitted, withExample } from "../text.js";
4
+ import { codeList, fitted, waysHint } from "../text.js";
5
5
  /**
6
6
  * Error boundary fallbacks, checked as catches (`errors/catch-misses-error`; they were
7
7
  * `errors/exhaustive-fallback` in earlier releases): a fallback that branches on the error with
8
8
  * `instanceof` handles every class its boundary can catch, or has a branch for the rest.
9
9
  */
10
- /** What the fallback does with any other error, in the example: what it returns or does. */
10
+ /**
11
+ * What the fallback does with any other error, as lines of code; undefined where the line depends
12
+ * on the boundary's own state, which is said in words.
13
+ */
11
14
  function restLine(kind, variable) {
12
15
  switch (kind) {
13
16
  case "FallbackComponent":
@@ -16,24 +19,42 @@ function restLine(kind, variable) {
16
19
  case "onError":
17
20
  return `console.error(${variable});`;
18
21
  case "getDerivedStateFromError":
19
- return `return { error: ${variable} };`;
22
+ return undefined;
20
23
  default: {
21
24
  const unreachable = kind;
22
25
  return unreachable;
23
26
  }
24
27
  }
25
28
  }
26
- function hint(fallback, chain, handler, count) {
27
- const line = `add a branch for ${count === 1 ? "it" : "each"}, or end with one for any other error:`;
29
+ /** The ways to handle the classes a fallback leaves out: a branch each, a branch for the rest, or the option. */
30
+ function hint(fallback, chain, handlers) {
31
+ const [handler = ""] = handlers;
32
+ const count = handlers.length;
28
33
  const rest = restLine(fallback.kind, chain.variable);
29
- return chain.dispatch === "switch"
30
- ? withExample(line, [
31
- `case ${chain.variable} instanceof ${handler}:`,
32
- " …",
33
- "default:",
34
- ` ${rest}`,
35
- ])
36
- : withExample(line, [`if (${chain.variable} instanceof ${handler}) {`, " …", "}", rest]);
34
+ const branch = chain.dispatch === "switch"
35
+ ? [`case ${chain.variable} instanceof ${handler}:`, " …"]
36
+ : [`if (${chain.variable} instanceof ${handler}) {`, " …", "}"];
37
+ const other = chain.dispatch === "switch"
38
+ ? ["default:", ...(rest === undefined ? [] : [` ${rest}`])]
39
+ : [rest];
40
+ const ignored = `{ ignoreClasses: [${handlers.map((one) => JSON.stringify(one)).join(", ")}] }`;
41
+ return waysHint([
42
+ { text: `add a branch for ${count === 1 ? "it" : "each"}`, example: branch },
43
+ rest === undefined
44
+ ? {
45
+ text: "end with one for any other error, returning the state the boundary shows for a failure",
46
+ }
47
+ : {
48
+ text: "end with one for any other error",
49
+ example: other.filter((line) => line !== undefined),
50
+ },
51
+ {
52
+ text: count === 1
53
+ ? `if \`${handler}\` needs no branch, list it under the rule's \`ignoreClasses\` option`
54
+ : "if they need no branch, list them under the rule's `ignoreClasses` option",
55
+ example: [ignored],
56
+ },
57
+ ]);
37
58
  }
38
59
  /** Reports each fallback that leaves out a class its boundary can catch. */
39
60
  export function checkFallbacks(model, ignored, report) {
@@ -73,7 +94,7 @@ export function checkFallbacks(model, ignored, report) {
73
94
  });
74
95
  report({
75
96
  message: fitted((cut) => `\`${cut(fallback.name)}\` does not handle ${codeList(missing.map((one) => one.name), cut)}, which its boundary can catch`),
76
- hint: hint(fallback, chain, catchName(first.id, classes), missing.length),
97
+ hint: hint(fallback, chain, missing.map((one) => catchName(one.id, classes))),
77
98
  location: { file, start: fallback.at[0], end: fallback.at[1] },
78
99
  related,
79
100
  });
@@ -24,6 +24,16 @@ export type TreeRender = {
24
24
  /** The tag as written. */
25
25
  readonly name: string;
26
26
  readonly at: Span;
27
+ /** The element as written when it is self-closing and short: what a hint wraps. */
28
+ readonly text?: string;
29
+ /**
30
+ * The nearest element around it, in the same component, that is named like an error boundary
31
+ * and comes from a package: an unlisted boundary, which the `boundaries` option would list.
32
+ */
33
+ readonly wrapper?: {
34
+ readonly tag: string;
35
+ readonly package: string;
36
+ };
27
37
  readonly around: readonly Around[];
28
38
  /**
29
39
  * The element goes where stateward cannot follow it (passed to a function, stored in an
@@ -1,5 +1,6 @@
1
1
  import ts from "@stateward/core/typescript";
2
- import { classIdOf, packageNameOf } from "../inference/summarize.js";
2
+ import { packageNameOf } from "@stateward/core";
3
+ import { errorClassIdOf } from "../inference/summarize.js";
3
4
  import { each, fieldsOf, isString, readStrings, spanOf } from "../inference/summary.js";
4
5
  import { scanRunning, stripParentheses } from "../syntax.js";
5
6
  import { ALL_GUARDS, guardThrows } from "./render-guards.js";
@@ -80,6 +81,17 @@ function tagName(tag) {
80
81
  return /^[a-z]/.test(tag.text) ? undefined : tag;
81
82
  return ts.isPropertyAccessExpression(tag) ? tag.name : undefined;
82
83
  }
84
+ /** What names a component that is likely an error boundary. */
85
+ const BOUNDARY_NAME = /boundary|catch/i;
86
+ /** The longest element a hint quotes whole. */
87
+ const TEXT_MAX = 60;
88
+ /** A self-closing element on one line as written, or undefined: what a hint can wrap as it is. */
89
+ function selfClosingText(element, sourceFile) {
90
+ if (!ts.isJsxSelfClosingElement(element))
91
+ return undefined;
92
+ const text = element.getText(sourceFile);
93
+ return text.length <= TEXT_MAX && !text.includes("\n") ? text : undefined;
94
+ }
83
95
  function openingOf(element) {
84
96
  return ts.isJsxElement(element) ? element.openingElement : element;
85
97
  }
@@ -99,7 +111,7 @@ function classifyTag(types, tag, libraryBoundaries) {
99
111
  }
100
112
  if (!types.isOwnFile(declaration.file)) {
101
113
  const library = packageNameOf(types, declaration.file);
102
- const isLibraryBoundary = (libraryBoundaries[library] ?? []).includes(symbol.name);
114
+ const isLibraryBoundary = library !== undefined && (libraryBoundaries[library] ?? []).includes(symbol.name);
103
115
  return { target: undefined, boundary: isLibraryBoundary ? { own: null } : undefined };
104
116
  }
105
117
  return {
@@ -359,7 +371,7 @@ function chainOf(types, fn, ref) {
359
371
  return null;
360
372
  const { classes, ...rest } = found;
361
373
  const branches = classes.map((names) => {
362
- const ids = names.map((name) => classIdOf(types, ts.isPropertyAccessExpression(name) ? name.name : name));
374
+ const ids = names.map((name) => errorClassIdOf(types, ts.isPropertyAccessExpression(name) ? name.name : name));
363
375
  return ids.every((id) => id !== undefined) ? ids : null;
364
376
  });
365
377
  return { ...rest, file: fn.getSourceFile().fileName, branches };
@@ -611,6 +623,25 @@ export function summarizeTree(ctx, libraryBoundaries = LIBRARY_BOUNDARIES, skips
611
623
  };
612
624
  walk(root);
613
625
  };
626
+ /** The nearest element around `element`, up to `stop`, named like a boundary and from a package. */
627
+ const wrapperOf = (element, stop) => {
628
+ for (let node = element.parent; node !== stop && !ts.isSourceFile(node); node = node.parent) {
629
+ if (!ts.isJsxElement(node))
630
+ continue;
631
+ const name = tagName(node.openingElement.tagName);
632
+ const symbol = name === undefined ? undefined : types.symbolAt(name);
633
+ const declaration = symbol === undefined ? undefined : types.declarationOf(symbol);
634
+ if (symbol === undefined || declaration === undefined)
635
+ continue;
636
+ if (types.isOwnFile(declaration.file) || !BOUNDARY_NAME.test(symbol.name))
637
+ continue;
638
+ const library = packageNameOf(types, declaration.file);
639
+ if (library === undefined)
640
+ continue;
641
+ return { tag: symbol.name, package: library };
642
+ }
643
+ return undefined;
644
+ };
614
645
  const rendersOf = (element, stop) => {
615
646
  const opening = openingOf(element);
616
647
  const tag = tagOf(opening);
@@ -619,6 +650,7 @@ export function summarizeTree(ctx, libraryBoundaries = LIBRARY_BOUNDARIES, skips
619
650
  key: keyOf(element),
620
651
  name: opening.tagName.getText(sourceFile),
621
652
  at: spanOf(opening.tagName),
653
+ ...(tag.boundary.own === null ? {} : { own: true }),
622
654
  fallbacks: fallbacksOf(types, opening, tag, sourceFile),
623
655
  });
624
656
  }
@@ -626,6 +658,8 @@ export function summarizeTree(ctx, libraryBoundaries = LIBRARY_BOUNDARIES, skips
626
658
  if (target === undefined)
627
659
  return [];
628
660
  const seen = new Set();
661
+ const text = selfClosingText(element, sourceFile);
662
+ const wrapper = wrapperOf(element, stop);
629
663
  return placementsOf(element, stop).flatMap((around) => {
630
664
  const key = JSON.stringify(around);
631
665
  if (seen.has(key))
@@ -636,6 +670,8 @@ export function summarizeTree(ctx, libraryBoundaries = LIBRARY_BOUNDARIES, skips
636
670
  target,
637
671
  name: opening.tagName.getText(sourceFile),
638
672
  at: spanOf(opening),
673
+ ...(text === undefined ? {} : { text }),
674
+ ...(wrapper === undefined ? {} : { wrapper }),
639
675
  around: around ?? [],
640
676
  unknown: around === null,
641
677
  },
@@ -771,9 +807,20 @@ function readRender(value) {
771
807
  return undefined;
772
808
  if (typeof f.unknown !== "boolean")
773
809
  return undefined;
774
- return isString(f.target) && isString(f.name)
775
- ? { target: f.target, name: f.name, at, around, unknown: f.unknown }
776
- : undefined;
810
+ if (!isString(f.target) || !isString(f.name))
811
+ return undefined;
812
+ const wrapper = f.wrapper === undefined ? undefined : fieldsOf(f.wrapper);
813
+ return {
814
+ target: f.target,
815
+ name: f.name,
816
+ at,
817
+ ...(isString(f.text) ? { text: f.text } : {}),
818
+ ...(isString(wrapper?.tag) && isString(wrapper.package)
819
+ ? { wrapper: { tag: wrapper.tag, package: wrapper.package } }
820
+ : {}),
821
+ around,
822
+ unknown: f.unknown,
823
+ };
777
824
  }
778
825
  function readChain(value) {
779
826
  if (value === null)
@@ -816,7 +863,7 @@ function readBoundary(value) {
816
863
  if (f === undefined || at === undefined || fallbacks === undefined)
817
864
  return undefined;
818
865
  return isString(f.key) && isString(f.name)
819
- ? { key: f.key, name: f.name, at, fallbacks }
866
+ ? { key: f.key, name: f.name, at, ...(f.own === true ? { own: true } : {}), fallbacks }
820
867
  : undefined;
821
868
  }
822
869
  const KINDS = ["component", "hook", "class"];
package/dist/refactors.js CHANGED
@@ -56,11 +56,44 @@ export const codeActions = (input) => {
56
56
  location: { file: input.file, start: offset, end: offset },
57
57
  newText,
58
58
  });
59
+ const lineStart = sourceFile.text.lastIndexOf("\n", clause.getStart(sourceFile)) + 1;
60
+ const base = /^[ \t]*/.exec(sourceFile.text.slice(lineStart))?.[0] ?? "";
61
+ const [first] = clause.block.statements;
62
+ const firstIndent = first === undefined
63
+ ? ""
64
+ : (/^[ \t]*/.exec(sourceFile.text.slice(sourceFile.text.lastIndexOf("\n", first.getStart(sourceFile)) + 1))?.[0] ?? "");
65
+ const unit = firstIndent.startsWith(base) && firstIndent.length > base.length
66
+ ? firstIndent.slice(base.length)
67
+ : " ";
68
+ const inner = `${base}${unit}`;
69
+ const body = sourceFile.text.slice(open + 1, close - 1);
70
+ // A text that spans lines (a template literal) must keep its own lines: the body is then left
71
+ // as written, with only the lines around it indented.
72
+ const spansLines = (node) => ((ts.isTemplateLiteral(node) || ts.isStringLiteralLike(node)) &&
73
+ node.getText(sourceFile).includes("\n")) ||
74
+ ts.forEachChild(node, spansLines) === true;
75
+ if (spansLines(clause.block)) {
76
+ actions.push({
77
+ title: HANDLE_KNOWN_TITLE,
78
+ edits: [
79
+ at(open + 1, `\n${inner}if (${tests}) {`),
80
+ at(close - 1, `${inner}} else {\n${inner}${unit}throw ${variable};\n${inner}}\n${base}`),
81
+ ],
82
+ });
83
+ continue;
84
+ }
85
+ const indented = body
86
+ .split("\n")
87
+ .map((line) => (line.trim() === "" ? line : `${unit}${line}`))
88
+ .join("\n")
89
+ .replace(/\s+$/, "");
59
90
  actions.push({
60
91
  title: HANDLE_KNOWN_TITLE,
61
92
  edits: [
62
- at(open + 1, `\nif (${tests}) {`),
63
- at(close - 1, `\n} else {\nthrow ${variable};\n}\n`),
93
+ {
94
+ location: { file: input.file, start: open + 1, end: close - 1 },
95
+ newText: `\n${inner}if (${tests}) {${indented}\n${inner}} else {\n${inner}${unit}throw ${variable};\n${inner}}\n${base}`,
96
+ },
64
97
  ],
65
98
  });
66
99
  }
@@ -3,9 +3,18 @@ export declare const GROUP = "render";
3
3
  /** The reason `plan` gives when a root boundary makes the rule silent. */
4
4
  export declare const ROOT_BOUNDARY_SILENT = "your app's root has an error boundary";
5
5
  export declare const renderThrowWithoutBoundary: import("@stateward/core").ProjectRule<import("./react/boundaries.js").ReactSummary, {
6
- skipContextGuards: import("@stateward/core").BooleanOption;
7
- skipInputGuards: import("@stateward/core").BooleanOption;
8
- rootBoundaryCounts: import("@stateward/core").BooleanOption;
6
+ skipContextGuards: import("@stateward/core").BooleanOption & Pick<{
7
+ readonly default: true;
8
+ readonly description: "Leave out the usual check in a context hook: `if (!ctx) throw new Error(\"useAuth must be used within AuthProvider\")`.";
9
+ }, "internal">;
10
+ skipInputGuards: import("@stateward/core").BooleanOption & Pick<{
11
+ readonly default: true;
12
+ readonly description: "Leave out a throw when a prop or a parameter whose type rules it out, or a context hook's value, is missing (a mistake of the caller).";
13
+ }, "internal">;
14
+ rootBoundaryCounts: import("@stateward/core").BooleanOption & Pick<{
15
+ readonly default: false;
16
+ readonly description: "Count the error boundary around the whole app as handling the error. Off by default: the whole app is then replaced by its fallback, so the rule asks for a boundary nearer the page.";
17
+ }, "internal">;
9
18
  boundaries: import("@stateward/core").RecordOption;
10
- }, "render">;
19
+ }, "render", Readonly<Record<string, import("@stateward/core").Json>>>;
11
20
  //# sourceMappingURL=render-throw-without-boundary.d.ts.map
@@ -2,7 +2,7 @@ import { defineRule, highestUncovered, option, shortestPath } from "@stateward/c
2
2
  import { className } from "./inference/format.js";
3
3
  import { modelOf, summarizeReact } from "./react/boundaries.js";
4
4
  import { LIBRARY_BOUNDARIES } from "./react/tree.js";
5
- import { codeList, fitted, withExample } from "./text.js";
5
+ import { codeList, fitted, waysHint } from "./text.js";
6
6
  /** The group the rule belongs to in the docs and in `stateward status`. */
7
7
  export const GROUP = "render";
8
8
  const EXPLAIN = `# errors/render-throw-without-boundary
@@ -60,6 +60,8 @@ createRoot(document.body).render(<App />);
60
60
 
61
61
  There is no quick fix: where the boundary goes, and what it shows, is your call.
62
62
 
63
+ The message offers the ways it can be fixed, with your own element as it is written. When the finding is at the app's own render, it points to the render below it that throws (a boundary around the whole app is not counted, see below), and to \`rootBoundaryCounts\` for one fallback for the whole app. If a component around it from another package is an error boundary, it shows the \`boundaries\` option with that package added to the ones already there. Where the project already has an error boundary, it names that one; where it has none, react-error-boundary's \`ErrorBoundary\` (imported as a value) or a class of yours with \`getDerivedStateFromError\`.
64
+
63
65
  ## Why it matters
64
66
 
65
67
  When a component throws while React renders it, or in one of its effects, React unmounts everything up to the nearest error boundary. With no boundary above, the whole app goes blank: a \`<UserPage>\` that throws \`NotFoundError\` for a wrong id takes the menu and every other route down with it, where a boundary could have shown "this user does not exist".
@@ -100,18 +102,104 @@ function headline(component, names) {
100
102
  function rootHeadline(component, names) {
101
103
  return fitted((cut) => `\`<${cut(component)}>\` can throw ${codeList(names, cut)} while rendering; only the app-wide boundary catches it`);
102
104
  }
103
- function rootHint(component) {
104
- return withExample("add a boundary around it, or set `rootBoundaryCounts` if replacing the whole app is intended:", ["<ErrorBoundary FallbackComponent={ErrorPage}>", ` <${component} />`, "</ErrorBoundary>"]);
105
- }
106
105
  /** The reason `plan` gives when a root boundary makes the rule silent. */
107
106
  export const ROOT_BOUNDARY_SILENT = "your app's root has an error boundary";
108
- function hint(component) {
109
- return withExample("wrap it in an error boundary, at this render or nearer to what throws; for example with react-error-boundary:", ["<ErrorBoundary FallbackComponent={ErrorPage}>", ` <${component} />`, "</ErrorBoundary>"]);
107
+ /** The error boundaries the project already renders, by name (its own classes and packages'). */
108
+ function boundaryNames(model) {
109
+ return [...new Set([...model.boundaries.values()].map((one) => one.element.name))].sort();
110
+ }
111
+ /** The `fallback` a wrapped example shows: the boundary's own prop, with the text left to the project. */
112
+ const FALLBACK = "fallback={<p>Something went wrong.</p>}";
113
+ /** `render` inside react-error-boundary's `ErrorBoundary`, or undefined when the element is too long to quote. */
114
+ function wrapped(render) {
115
+ return render.text === undefined
116
+ ? undefined
117
+ : [`<ErrorBoundary ${FALLBACK}>`, ` ${render.text}`, "</ErrorBoundary>"];
118
+ }
119
+ /** Wrap `render` in an error boundary: the project's own when it has one, else react-error-boundary's. */
120
+ function wrapWay(model, render, where) {
121
+ const known = boundaryNames(model);
122
+ const [first] = known;
123
+ if (first !== undefined) {
124
+ return {
125
+ text: `wrap \`<${render.name}>\` in \`${first}\`, which the project already uses${where}`,
126
+ };
127
+ }
128
+ const lines = wrapped(render);
129
+ const from = "react-error-boundary's `ErrorBoundary` (imported as a value), or a class of yours with `getDerivedStateFromError`";
130
+ return lines === undefined
131
+ ? { text: `wrap \`<${render.name}>\` and what it contains in ${from}${where}` }
132
+ : { text: `wrap it in ${from}${where}`, example: lines };
133
+ }
134
+ /** An element around the render that is named like an error boundary from a package: list it under `boundaries`. */
135
+ function listedWay(render, listed) {
136
+ const wrapper = render.wrapper;
137
+ if (wrapper === undefined || (listed[wrapper.package] ?? []).includes(wrapper.tag)) {
138
+ return undefined;
139
+ }
140
+ const merged = {};
141
+ for (const [name, tags] of Object.entries(listed))
142
+ merged[name] = [...tags];
143
+ merged[wrapper.package] = [...(merged[wrapper.package] ?? []), wrapper.tag];
144
+ const entries = Object.entries(merged).map(([name, tags]) => ` ${JSON.stringify(name)}: [${tags.map((one) => JSON.stringify(one)).join(", ")}],`);
145
+ const text = `if \`<${wrapper.tag}>\` from \`${wrapper.package}\` is an error boundary, add it to the \`boundaries\` option, next to the ones already there`;
146
+ // The example is at most four lines: a longer list is described instead.
147
+ return entries.length <= 2
148
+ ? { text, example: ["boundaries: {", ...entries, "}"] }
149
+ : { text: `${text}: ${JSON.stringify(wrapper.package)}: [${JSON.stringify(wrapper.tag)}]` };
150
+ }
151
+ /** Wrap an entry's own render: only a boundary the app-wide option counts. */
152
+ function rootWay(model, render) {
153
+ const lines = boundaryNames(model).length === 0 ? wrapped(render) : undefined;
154
+ const text = "if one fallback for the whole app is what you want, wrap it and set the `rootBoundaryCounts` option to `true`";
155
+ return lines === undefined ? { text } : { text, example: lines };
156
+ }
157
+ /** The ways to put an error boundary where the render has none above it. */
158
+ function ways(place, root) {
159
+ const { model, site, below, isEntry } = place;
160
+ const listed = (render) => {
161
+ const way = listedWay(render, place.options.boundaries);
162
+ return way === undefined ? [] : [way];
163
+ };
164
+ if (isEntry && below !== undefined) {
165
+ // A boundary around the whole app is not counted: the way out is the render below it.
166
+ const render = below.render;
167
+ return waysHint([
168
+ wrapWay(model, render, ", not around the whole app"),
169
+ rootWay(model, site.render),
170
+ ...listed(render),
171
+ ]);
172
+ }
173
+ if (isEntry) {
174
+ return waysHint([
175
+ {
176
+ text: "move what `<" +
177
+ site.render.name +
178
+ ">` throws into a component it renders, and wrap that render in an error boundary",
179
+ },
180
+ rootWay(model, site.render),
181
+ ]);
182
+ }
183
+ const own = wrapWay(model, site.render, ", at this render or nearer to what throws");
184
+ return waysHint([
185
+ own,
186
+ ...(root
187
+ ? [
188
+ {
189
+ text: "if replacing the whole app by its fallback is intended, set the `rootBoundaryCounts` option to `true`: the boundary around the app then counts",
190
+ },
191
+ ]
192
+ : []),
193
+ ...listed(site.render),
194
+ ]);
195
+ }
196
+ /** The renders down from the site to the component that throws `cls`; undefined when none is found. */
197
+ function pathTo(model, site, cls) {
198
+ return shortestPath(site.to, (id) => model.edges(id), (edge) => model.nearest(edge) === undefined && model.needs(edge.to).has(cls), (id) => model.own(id).classes.get(cls)?.certain === true && !model.own(id).guarded.has(cls));
110
199
  }
111
200
  /** The renders down from the site to the component that throws `cls`, then the call that throws it. */
112
- function pathNotes(model, site, cls) {
201
+ function pathNotes(model, site, cls, path) {
113
202
  const classes = model.analysis.classes;
114
- const path = shortestPath(site.to, (id) => model.edges(id), (edge) => model.nearest(edge) === undefined && model.needs(edge.to).has(cls), (id) => model.own(id).classes.get(cls)?.certain === true && !model.own(id).guarded.has(cls));
115
203
  if (path === undefined)
116
204
  return [];
117
205
  const notes = path.map((edge) => ({
@@ -228,11 +316,13 @@ export const renderThrowWithoutBoundary = defineRule({
228
316
  continue;
229
317
  const component = model.functions.get(edge.to)?.fn.name ?? edge.render.name;
230
318
  const names = named.map((one) => one.name);
319
+ const path = pathTo(model, edge, first.id);
320
+ const isEntry = model.entries.some((entry) => entry.file === edge.file && entry.render.at[0] === edge.render.at[0]);
231
321
  ctx.report({
232
322
  message: root ? rootHeadline(component, names) : headline(component, names),
233
- hint: root ? rootHint(edge.render.name) : hint(edge.render.name),
323
+ hint: ways({ model, options: ctx.options, site: edge, below: path?.[0], isEntry }, root),
234
324
  location: { file: edge.file, start: edge.render.at[0], end: edge.render.at[1] },
235
- related: pathNotes(model, edge, first.id),
325
+ related: pathNotes(model, edge, first.id, path),
236
326
  });
237
327
  }
238
328
  },
@@ -1,5 +1,8 @@
1
1
  export declare const resultIgnored: import("@stateward/core").FileRule<{
2
- allowVoid: import("@stateward/core").BooleanOption;
2
+ allowVoid: import("@stateward/core").BooleanOption & Pick<{
3
+ readonly default: false;
4
+ readonly description: "Take `void save()` as dropping the Result on purpose, and stay quiet.";
5
+ }, "internal">;
3
6
  resultTypes: import("@stateward/core").StringsOption;
4
7
  ignore: import("@stateward/core").StringsOption;
5
8
  }, "callers">;
@@ -1,6 +1,6 @@
1
1
  import ts from "@stateward/core/typescript";
2
2
  import { defineRule, matchesName, option } from "@stateward/core";
3
- import { example, resultShapeOf, shorten } from "./result-type.js";
3
+ import { example, freeName, resultShapeOf, shorten } from "./result-type.js";
4
4
  const EXPLAIN = `# errors/result-ignored
5
5
 
6
6
  A \`Result\` dropped as a statement discards its error, so a failed call looks the same as a successful one.
@@ -29,7 +29,7 @@ export async function rename(name: string): Promise<Result<void>> {
29
29
  }
30
30
  \`\`\`
31
31
 
32
- The message shows how, with your names and your Result's shape. There is no quick fix.
32
+ The message shows how, with your names and your Result's shape: the check, and \`return\` of it only where the function returns that Result. If the drop is on purpose, it says so in the rule's options: \`allowVoid\` for \`void save()\`, \`ignore\` for a function that may always be dropped. There is no quick fix.
33
33
 
34
34
  ## Why it matters
35
35
 
@@ -92,14 +92,14 @@ function isVoided(expression) {
92
92
  isVoided(expression.expression));
93
93
  }
94
94
  /** The line of the example that checks the result, in the Result's own shape. */
95
- function checkLine(shape) {
95
+ function checkLine(shape, name, returnsIt) {
96
96
  switch (shape) {
97
97
  case "ok":
98
- return "if (!saved.ok) return saved;";
98
+ return returnsIt ? `if (!${name}.ok) return ${name};` : `if (!${name}.ok) { … }`;
99
99
  case "success":
100
- return "if (!saved.success) return saved;";
100
+ return returnsIt ? `if (!${name}.success) return ${name};` : `if (!${name}.success) { … }`;
101
101
  case "isErr":
102
- return "if (saved.isErr()) return saved;";
102
+ return returnsIt ? `if (${name}.isErr()) return ${name};` : `if (${name}.isErr()) { … }`;
103
103
  case "named":
104
104
  return "// handle its failure here, or return it";
105
105
  default: {
@@ -108,6 +108,27 @@ function checkLine(shape) {
108
108
  }
109
109
  }
110
110
  }
111
+ /** `Result<void, E>` of `Promise<Result<void, E>>`: the type of what the call gives once awaited. */
112
+ function awaitedText(text) {
113
+ const match = /^(?:Promise|PromiseLike)<(.*)>$/.exec(text.trim());
114
+ return (match?.[1] ?? text).trim();
115
+ }
116
+ /**
117
+ * Whether returning the checked Result is valid code here: the function declares the type the
118
+ * call gives (once awaited), so the failed branch of it is what the function returns.
119
+ */
120
+ function returnsSameResult(call, fn, ctx) {
121
+ if (fn?.type === undefined)
122
+ return false;
123
+ return awaitedText(ctx.types.typeTextOf(fn.type)) === awaitedText(ctx.types.typeTextOf(call));
124
+ }
125
+ /** Whether `await` is valid where the statement is: in an async function, or at a module's top. */
126
+ function canAwait(fn) {
127
+ if (fn === undefined)
128
+ return true;
129
+ const modifiers = ts.canHaveModifiers(fn) ? ts.getModifiers(fn) : undefined;
130
+ return modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword) === true;
131
+ }
111
132
  function checkStatement(statement, ctx) {
112
133
  if (ctx.options.allowVoid && isVoided(statement.expression))
113
134
  return;
@@ -126,14 +147,34 @@ function checkStatement(statement, ctx) {
126
147
  const callText = whole.length > CALL_MAX
127
148
  ? `${shorten(call.expression.getText(ctx.sourceFile), CALL_MAX)}(…)`
128
149
  : whole;
150
+ const fn = ts.findAncestor(statement.parent, ts.isFunctionLike);
151
+ const name = freeName(fn ?? ctx.sourceFile, ctx.sourceFile, [
152
+ "saved",
153
+ "result",
154
+ "outcome",
155
+ "checked",
156
+ ]);
157
+ const returnsIt = returnsSameResult(call, fn, ctx);
158
+ const needsAsync = promised && !canAwait(fn);
159
+ const handled = returnsIt
160
+ ? "check it, and pass it on"
161
+ : "check it, and handle its failure (report it, recover, or pass it on from a function that returns a Result)";
162
+ const ways = [
163
+ `- ${handled}${needsAsync ? "; `await` needs the function to be `async`" : ""}`,
164
+ example([
165
+ `const ${name} = ${promised ? "await " : ""}${callText};`,
166
+ checkLine(shape, name, returnsIt),
167
+ ]),
168
+ isVoided(statement.expression)
169
+ ? "- or, if dropping it is on purpose, set the rule's `allowVoid` option to `true`: a `void` drop is then stated"
170
+ : "- or, if dropping it is on purpose, write `void` before the call and set the rule's `allowVoid` option to `true`",
171
+ `- or, if \`${callee}\` may always be dropped, list it under the rule's \`ignore\` option`,
172
+ ];
129
173
  ctx.report({
130
174
  node: statement,
131
175
  about: statement,
132
176
  message: `the \`Result\` of \`${calleeText(call, ctx)}(…)\` is dropped: its error is never handled`,
133
- hint: [
134
- "check it, or pass it on:",
135
- example([`const saved = ${promised ? "await " : ""}${callText};`, checkLine(shape)]),
136
- ].join("\n"),
177
+ hint: ["one of", ...ways].join("\n"),
137
178
  });
138
179
  }
139
180
  export const resultIgnored = defineRule({
@@ -15,4 +15,6 @@ export declare function resultShapeOf(node: ts.Node, types: TypeQueries, names:
15
15
  export declare function shorten(text: string, max: number): string;
16
16
  /** A hint's example: indented 4 spaces, one line per entry. */
17
17
  export declare function example(lines: readonly string[]): string;
18
+ /** The first of `names` that the code under `scope` does not use already, so an example never shadows one. */
19
+ export declare function freeName(scope: ts.Node, sourceFile: ts.SourceFile, names: readonly string[]): string;
18
20
  //# sourceMappingURL=result-type.d.ts.map
@@ -1,4 +1,4 @@
1
- import { matchesName } from "@stateward/core";
1
+ import { codeOnOneLine, matchesName } from "@stateward/core";
2
2
  /**
3
3
  * Whether a property tells the members of a union apart by `true` and `false`. An object with
4
4
  * `ok: boolean` (a fetch `Response`) is not a union, so it is not a Result.
@@ -45,11 +45,17 @@ export function resultShapeOf(node, types, names) {
45
45
  }
46
46
  /** Cuts `text` to `max` characters, ending in `…`, for a headline or an example line. */
47
47
  export function shorten(text, max) {
48
- const flat = text.replace(/\s+/g, " ").trim();
48
+ const flat = codeOnOneLine(text);
49
49
  return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
50
50
  }
51
51
  /** A hint's example: indented 4 spaces, one line per entry. */
52
52
  export function example(lines) {
53
53
  return lines.map((line) => ` ${line}`).join("\n");
54
54
  }
55
+ /** The first of `names` that the code under `scope` does not use already, so an example never shadows one. */
56
+ export function freeName(scope, sourceFile, names) {
57
+ const text = scope.getText(sourceFile);
58
+ const free = names.find((name) => !new RegExp(`\\b${name}\\b`).test(text));
59
+ return free ?? `${names[0] ?? "result"}Checked`;
60
+ }
55
61
  //# sourceMappingURL=result-type.js.map
@@ -1,2 +1,5 @@
1
- export declare const resultUnchecked: import("@stateward/core").FileRule<Readonly<Record<string, never>>, "callers">;
1
+ export declare const resultUnchecked: import("@stateward/core").FileRule<{
2
+ failureNames: import("@stateward/core").StringsOption;
3
+ successNames: import("@stateward/core").StringsOption;
4
+ }, "callers">;
2
5
  //# sourceMappingURL=result-unchecked.d.ts.map