@stateward/plugin-errors 1.2.2 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) 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 +12 -5
  4. package/dist/catch-misses-error.d.ts +1 -1
  5. package/dist/catch-misses-error.js +7 -4
  6. package/dist/finally-can-throw.js +3 -3
  7. package/dist/hover.js +6 -9
  8. package/dist/index.d.ts +3 -1
  9. package/dist/index.js +1 -0
  10. package/dist/inference/analysis.d.ts +109 -0
  11. package/dist/inference/analysis.js +170 -0
  12. package/dist/inference/builtins.d.ts +0 -2
  13. package/dist/inference/builtins.js +0 -33
  14. package/dist/inference/deps.d.ts +13 -2
  15. package/dist/inference/deps.js +24 -13
  16. package/dist/inference/needs.d.ts +16 -0
  17. package/dist/inference/needs.js +27 -0
  18. package/dist/inference/packages.d.ts +24 -32
  19. package/dist/inference/packages.js +156 -680
  20. package/dist/inference/project.d.ts +4 -4
  21. package/dist/inference/project.js +6 -17
  22. package/dist/inference/solve.d.ts +29 -4
  23. package/dist/inference/solve.js +42 -12
  24. package/dist/inference/summarize.d.ts +27 -15
  25. package/dist/inference/summarize.js +247 -130
  26. package/dist/inference/summary.d.ts +41 -5
  27. package/dist/inference/summary.js +84 -12
  28. package/dist/inference/unreachable.d.ts +5 -0
  29. package/dist/inference/unreachable.js +160 -0
  30. package/dist/inlay.d.ts +1 -5
  31. package/dist/inlay.js +1 -12
  32. package/dist/must-handle-error.d.ts +4 -3
  33. package/dist/must-handle-error.js +10 -13
  34. package/dist/plugin.d.ts +12 -2
  35. package/dist/plugin.js +4 -2
  36. package/dist/react/boundaries.d.ts +9 -7
  37. package/dist/react/boundaries.js +16 -24
  38. package/dist/react/tree.js +8 -4
  39. package/dist/refactors.js +1 -1
  40. package/dist/render-throw-without-boundary.d.ts +13 -4
  41. package/dist/render-throw-without-boundary.js +4 -2
  42. package/dist/result-ignored.d.ts +4 -1
  43. package/dist/result-type.js +2 -2
  44. package/dist/result-unchecked.d.ts +4 -1
  45. package/dist/result-unchecked.js +139 -61
  46. package/dist/rules.meta.d.ts +26 -14
  47. package/dist/rules.meta.js +18 -14
  48. package/dist/syntax.d.ts +0 -13
  49. package/dist/syntax.js +0 -79
  50. package/dist/text.d.ts +5 -2
  51. package/dist/text.js +11 -5
  52. package/dist/throws-doc-mismatch.d.ts +2 -2
  53. package/dist/throws-doc-mismatch.js +13 -5
  54. package/package.json +2 -2
package/README.md CHANGED
@@ -42,10 +42,11 @@ rules: {
42
42
  Add-on rules stay off until you list their add-on:
43
43
 
44
44
  ```ts
45
- addons: ["errors/narrow-try"],
45
+ addons: ["errors/catch-hides-unexpected", "errors/result-unchecked"],
46
46
  ```
47
47
 
48
- - `errors/narrow-try`: `narrow-try`
48
+ - `errors/catch-hides-unexpected`: `catch-hides-unexpected`
49
+ - `errors/result-unchecked`: `result-unchecked`
49
50
 
50
51
  Every key of the config: [config.md](https://github.com/khoing1111/ts-stateward/blob/main/docs/user/config.md).
51
52
 
@@ -55,22 +56,22 @@ Every key of the config: [config.md](https://github.com/khoing1111/ts-stateward/
55
56
 
56
57
  ## Rules
57
58
 
58
- | Rule | What it finds | Why it matters | Kind | `recommended` | `strict` |
59
+ | Rule | What it finds | Details | Kind | `recommended` | `strict` |
59
60
  | --- | --- | --- | --- | --- | --- |
60
61
  | [must-handle-error](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/must-handle-error.md) | a call that can throw an error marked `@mustHandle`, with no code that handles or passes it on | An error marked `@mustHandle` needs a decision at each call, such as a message to the user; a call that neither catches it nor passes it on lets it reach the top. | Core | error | error |
61
62
  | [result-ignored](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/result-ignored.md) | a `Result` dropped as a statement, after `void` or after `await` | A `Result` dropped as a statement discards its error, so a failed call looks the same as a successful one. | Core | error | error |
62
- | [result-unchecked](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/result-unchecked.md) | a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked (guess) | 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. | Core | warning | warning |
63
63
  | [throws-doc-mismatch](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/throws-doc-mismatch.md) | a `@throws` tag that lists an error the function cannot throw, or misses one it can | Callers decide what to catch from `@throws`: a class it omits reaches them unhandled, and a class listed in excess asks them to handle a case that cannot happen. | Core | error | error |
64
- | [catch-hides-unexpected](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/catch-hides-unexpected.md) | a `catch` that handles some error classes with `instanceof` and ignores the rest | A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible. | Core | error | error |
64
+ | [result-unchecked](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/result-unchecked.md) | a call that fails in its value (an RTK Query trigger, a Result) used as if it had worked (heuristic) | 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. | Add-on `result-unchecked` | warning | warning |
65
65
  | [catch-misses-error](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/catch-misses-error.md) | a `catch` that branches on error classes but misses one its `try` can throw | An error class the `try` can throw and the `catch` does not test goes to the generic branch, or is ignored; a branch for it, or a rethrow, handles it explicitly. | Core | error | error |
66
66
  | [finally-can-throw](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/finally-can-throw.md) | a `finally` that calls something that can throw and replace the original error | An error thrown in `finally` replaces the error that was already thrown, so the report names the cleanup instead of the original cause. | Core | error | error |
67
- | [narrow-try](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/narrow-try.md) | calls to your own code inside a `try` after the call it is for, so their bugs look like its failure | A bug in code inside a `try` meant for another call is caught and reported as that call's failure; moving the code after the `try` keeps the two apart. | Add-on `narrow-try` | warning | warning |
67
+ | [catch-hides-unexpected](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/catch-hides-unexpected.md) | a `catch` that handles some error classes with `instanceof` and ignores the rest | A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible. | Add-on `catch-hides-unexpected` | error | error |
68
68
  | [render-throw-without-boundary](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/errors/render-throw-without-boundary.md) | a component that can throw a known error while rendering, with no error boundary above it | An error thrown while rendering, with no error boundary above the component, unmounts the whole React tree and leaves a blank page. | Core | warning | warning |
69
69
 
70
70
  **Core** rules are on in every preset. **Coverage** rules point at code whose types do not say
71
71
  enough for stateward to check it; they are info under `recommended` and errors under `strict`.
72
- **Add-on** rules stay off until you list their add-on in `addons`; the table shows their severity
73
- once it is listed. A rule marked (guess) judges from patterns in the code, not only from types, so
72
+ **Convention** rules check a team convention, not a fact about the code: they stay off until the
73
+ config sets `conventions: true` or names the rule under `rules`; a convention rule that reads only what the project states is on, and silent until the project states something. **Add-on** rules stay off until
74
+ you list their add-on in `addons`. The table shows the severity of both once they are on. A rule marked (heuristic) judges from patterns in the code, not only from types, so
74
75
  it can be wrong and is never an error unless you make it one.
75
76
 
76
77
  Each rule's page shows an example with what stateward prints for it, the fix, why it matters, what it misses, and its options. The pack's page: [docs/packs/errors.md](https://github.com/khoing1111/ts-stateward/blob/main/docs/packs/errors.md). Every pack's rules: [the rules index](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/README.md).
@@ -1,6 +1,9 @@
1
1
  /** The group the rule belongs to in the docs and in `stateward status`. */
2
2
  export declare const GROUP = "catch";
3
3
  export declare const catchHidesUnexpected: import("@stateward/core").FileRule<{
4
- restUsesError: import("@stateward/core").BooleanOption;
4
+ restUsesError: import("@stateward/core").BooleanOption & Pick<{
5
+ readonly default: false;
6
+ readonly description: "The branch for the other errors must use the error (rethrow it, wrap it, report it); a generic message alone does not count.";
7
+ }, "internal">;
5
8
  }, "catch">;
6
9
  //# sourceMappingURL=catch-hides-unexpected.d.ts.map
@@ -1,9 +1,11 @@
1
1
  import ts from "@stateward/core/typescript";
2
- import { defineRule, option } from "@stateward/core";
2
+ import { codeOnOneLine, defineRule, option, offByDefaultText, } from "@stateward/core";
3
3
  import { stripParentheses } from "./syntax.js";
4
- import { codeList, fitted, oneLine, withExample } from "./text.js";
4
+ import { codeList, fitted, withExample } from "./text.js";
5
5
  /** The group the rule belongs to in the docs and in `stateward status`. */
6
6
  export const GROUP = "catch";
7
+ /** Off by default since 1.3: 4 of 7 of its findings checked on real projects were right. */
8
+ const OFF_BY_DEFAULT = { since: "1.3", right: 4, checked: 7 };
7
9
  const EXPLAIN = `# errors/catch-hides-unexpected
8
10
 
9
11
  A \`catch\` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible.
@@ -64,8 +66,11 @@ A \`catch\` that handles \`NotFoundError\` and \`AuthError\` and has no last bra
64
66
 
65
67
  ## Turn it on or off
66
68
 
69
+ ${offByDefaultText(OFF_BY_DEFAULT)}
70
+
67
71
  \`\`\`ts
68
- rules: { "errors/catch-hides-unexpected": "off" } // or "warning"
72
+ addons: ["errors/catch-hides-unexpected"]
73
+ rules: { "errors/catch-hides-unexpected": "warning" } // on, as a warning
69
74
  rules: { "errors/catch-hides-unexpected": ["error", { restUsesError: true }] } // the last branch must use the error
70
75
  \`\`\`
71
76
  `;
@@ -91,7 +96,7 @@ function instanceOfClasses(condition, variable, sourceFile) {
91
96
  if (operator === ts.SyntaxKind.InstanceOfKeyword) {
92
97
  const subject = stripParentheses(node.left);
93
98
  return ts.isIdentifier(subject) && subject.text === variable
94
- ? [oneLine(stripParentheses(node.right).getText(sourceFile))]
99
+ ? [codeOnOneLine(stripParentheses(node.right).getText(sourceFile))]
95
100
  : [];
96
101
  }
97
102
  if (operator === ts.SyntaxKind.BarBarToken ||
@@ -301,7 +306,9 @@ export const catchHidesUnexpected = defineRule({
301
306
  description: "A `catch` that tests some error classes and has no last branch ignores every other error, bugs included; rethrowing the rest keeps them visible.",
302
307
  summary: "a `catch` that handles some error classes with `instanceof` and ignores the rest",
303
308
  defaultSeverity: "error",
304
- tier: "core",
309
+ tier: "addon",
310
+ addon: "catch-hides-unexpected",
311
+ offByDefault: OFF_BY_DEFAULT,
305
312
  group: GROUP,
306
313
  options: OPTIONS,
307
314
  explain: EXPLAIN,
@@ -2,5 +2,5 @@
2
2
  export declare const GROUP = "catch";
3
3
  export declare const catchMissesError: import("@stateward/core").ProjectRule<import("./react/boundaries.js").ReactSummary, {
4
4
  ignoreClasses: import("@stateward/core").StringsOption;
5
- }, "catch">;
5
+ }, "catch", Readonly<Record<string, import("@stateward/core").Json>>>;
6
6
  //# sourceMappingURL=catch-misses-error.d.ts.map
@@ -1,7 +1,8 @@
1
1
  import { defineRule, matchesName, option } from "@stateward/core";
2
2
  import { catchName, className } from "./inference/format.js";
3
3
  import { analyse, everyCatch } from "./inference/solve.js";
4
- import { modelOf, summarizeReact, throwsOf } from "./react/boundaries.js";
4
+ import { THROWS_ANALYSIS } from "./inference/deps.js";
5
+ import { modelOf, summarizeReact } from "./react/boundaries.js";
5
6
  import { checkFallbacks } from "./react/fallbacks.js";
6
7
  import { codeList, fitted, withExample } from "./text.js";
7
8
  /** The group the rule belongs to in the docs and in `stateward status`. */
@@ -77,7 +78,7 @@ What counts as handled: \`e instanceof X\` handles \`X\` and every class that ex
77
78
 
78
79
  ## Getting the best from it
79
80
 
80
- What the \`try\` can throw is worked out from \`throw new X(…)\` in the functions it calls, in any file; their \`@throws {X}\` tags (also on a function with no body, such as \`declare function\` or a \`.d.ts\` of your own); the built-ins above; and the packages it calls (\`stateward deps\` shows how well each package's errors are known). So throw classes, not strings, and document what a function throws with \`@throws\`. Declare a package's errors under \`facts\` in the config: \`facts: { "config-lib": { load: { throws: ["ConfigError"] } } }\`.
81
+ What the \`try\` can throw is worked out from \`throw new X(…)\` in the functions it calls, in any file; their \`@throws {X}\` tags (also on a function with no body, such as \`declare function\` or a \`.d.ts\` of your own); the built-ins above; and the packages it calls, as their \`facts\` state (\`stateward deps\` shows how well each package's errors are known). A package is known by its types, the pack's model and your \`facts\`; its code and its doc comments are not read. So throw classes, not strings, and document what a function throws with \`@throws\`. Declare a package's errors under \`facts\` in the config: \`facts: { "config-lib": { load: { throws: ["ConfigError"] } } }\`.
81
82
 
82
83
  An error boundary's fallback is checked the same way: what the components below the boundary throw while rendering and in their effects, down to the next boundary, is its \`try\` (the hover on the boundary lists it). A fallback (react-error-boundary's \`FallbackComponent\`, \`fallbackRender\` or \`onError\`, or a boundary class's \`getDerivedStateFromError\`) that branches with \`if\` / \`else if\`, \`switch (true)\` or \`? :\` on \`error instanceof X\` needs a branch for each class the boundary can catch, or a branch for the rest that does more than return \`null\` or nothing. The message shows both, written for the kind of fallback (for a boundary class's \`getDerivedStateFromError\` it describes the branch for the rest, since the state is yours), and the \`ignoreClasses\` option with the class named. A fallback that does not branch on \`instanceof\`, whose tests are not only \`instanceof\`, or that is passed as anything other than a function written in place or the name of one of your functions, is left alone.
83
84
 
@@ -225,15 +226,17 @@ export const catchMissesError = defineRule({
225
226
  },
226
227
  explain: EXPLAIN,
227
228
  },
229
+ reads: [THROWS_ANALYSIS],
228
230
  summarize: (ctx) => summarizeReact(ctx),
229
231
  check(summaries, ctx) {
230
- const analysis = analyse(throwsOf(summaries));
232
+ const throws = ctx.analysisSummaries(THROWS_ANALYSIS);
233
+ const analysis = analyse(throws);
231
234
  for (const seen of everyCatch(analysis)) {
232
235
  report(seen, analysis.classes, ctx.options.ignoreClasses, (problem) => {
233
236
  ctx.report(problem);
234
237
  });
235
238
  }
236
- checkFallbacks(modelOf(summaries), ctx.options.ignoreClasses, (problem) => {
239
+ checkFallbacks(modelOf(summaries, throws), ctx.options.ignoreClasses, (problem) => {
237
240
  ctx.report(problem);
238
241
  });
239
242
  },
@@ -1,7 +1,7 @@
1
1
  import ts from "@stateward/core/typescript";
2
- import { defineRule, option } from "@stateward/core";
2
+ import { codeOnOneLine, defineRule, option } from "@stateward/core";
3
3
  import { hasModifier, isBuiltinGlobal, sameFileFunction, scanRunning, stripParentheses, throwsUncaught, } from "./syntax.js";
4
- import { fitted, oneLine, withExample } from "./text.js";
4
+ import { fitted, withExample } from "./text.js";
5
5
  /** The group the rule belongs to in the docs and in `stateward status`. */
6
6
  export const GROUP = "catch";
7
7
  const EXPLAIN = `# errors/finally-can-throw
@@ -122,7 +122,7 @@ function causeOf(node, awaited, ctx) {
122
122
  // An async function turns its throw into a rejected promise, which only an `await` rethrows.
123
123
  if (hasModifier(declared, ts.SyntaxKind.AsyncKeyword) && !awaited)
124
124
  return undefined;
125
- const callee = oneLine(stripParentheses(node.expression).getText(ctx.sourceFile));
125
+ const callee = codeOnOneLine(stripParentheses(node.expression).getText(ctx.sourceFile));
126
126
  return { node, subject: (cut) => `\`${cut(callee)}(…)\` can throw`, kind: "own-function" };
127
127
  }
128
128
  function headline(cause) {
package/dist/hover.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import ts from "@stateward/core/typescript";
2
- import { FACT_RULES } from "./inference/deps.js";
2
+ import { factSummaries } from "./inference/deps.js";
3
3
  import { resultLines } from "./inference/format.js";
4
4
  import { analyse } from "./inference/solve.js";
5
- import { TREE_RULES, boundaryLines, modelOf, throwsOf } from "./react/boundaries.js";
5
+ import { TREE_RULES, boundaryLines, modelOf } from "./react/boundaries.js";
6
6
  /** The identifier that covers `offset`, if any. */
7
7
  function identifierAt(root, offset) {
8
8
  if (offset < root.getStart() || offset >= root.getEnd())
@@ -32,20 +32,17 @@ function isFunctionName(identifier) {
32
32
  * not the project's own. On an error boundary's tag, what it catches (`boundaryLines`).
33
33
  */
34
34
  export const hover = (input) => {
35
+ const summaries = factSummaries(input);
36
+ if (summaries === undefined)
37
+ return undefined;
35
38
  let trees;
36
39
  for (const ruleId of TREE_RULES)
37
40
  trees ??= input.projectSummaries(ruleId);
38
41
  if (trees !== undefined) {
39
- const lines = boundaryLines(modelOf(trees), input.sourceFile.fileName, input.offset);
42
+ const lines = boundaryLines(modelOf(trees, summaries), input.sourceFile.fileName, input.offset);
40
43
  if (lines !== undefined)
41
44
  return lines.join("\n\n");
42
45
  }
43
- let summaries;
44
- for (const ruleId of FACT_RULES)
45
- summaries ??= input.projectSummaries(ruleId);
46
- summaries ??= trees === undefined ? undefined : throwsOf(trees);
47
- if (summaries === undefined)
48
- return undefined;
49
46
  const identifier = identifierAt(input.sourceFile, input.offset);
50
47
  if (identifier === undefined || !isFunctionName(identifier))
51
48
  return undefined;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  export { errors } from "./plugin.js";
2
+ export { decidingFacts } from "./inference/needs.js";
3
+ export type { DecidingFacts } from "./inference/needs.js";
2
4
  export type { ThrowsSummary } from "./inference/summary.js";
5
+ export type { ClassInfo, FunctionThrows, ThrowsAnalysis, ThrowsUnknown, ThrownClass, ThrowOrigin, ThrownErrors, UnknownFact, } from "./inference/analysis.js";
3
6
  export type { ReactSummary } from "./react/boundaries.js";
4
7
  export type { TreeSummary } from "./react/tree.js";
5
8
  export type { MustHandleSummary } from "./must-handle-error.js";
6
- export type { NarrowTrySummary } from "./narrow-try.js";
7
9
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export { errors } from "./plugin.js";
2
+ export { decidingFacts } from "./inference/needs.js";
2
3
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,109 @@
1
+ import type { FactKey, Json, Location, PluginAnalysis } from "@stateward/core";
2
+ import type { UnknownFact } from "./solve.js";
3
+ export type { UnknownFact };
4
+ /** A place the analysis could not follow, and why. */
5
+ export type ThrowsUnknown = {
6
+ readonly location: Location;
7
+ /** The code there, as written: `api.get(id)`. */
8
+ readonly text: string;
9
+ /** Why it is not followed: `no declaration`, `its errors are not stated`. */
10
+ readonly reason: string;
11
+ /**
12
+ * The package whose facts the unknown comes from, when it does: the module of the `facts` key
13
+ * that names the function (`axios`, `node:path`), else the package.
14
+ */
15
+ readonly package?: string;
16
+ /**
17
+ * What decides it: the `facts` line a package call needs (`unstated`, or `withheld` when the
18
+ * config's line is for other versions), a package call no key can name (`unnamed`), or a callee
19
+ * typed `any` (`untyped`). Absent for the other places.
20
+ */
21
+ readonly fact?: UnknownFact;
22
+ };
23
+ /**
24
+ * A class in a set of errors, by id: `builtin:TypeError` for a class of the platform (a named
25
+ * `DOMException` is `builtin:DOMException:AbortError`), `package:<name>#<class>` for a package's
26
+ * class, and the symbol id of a class of the project (`SymbolRef.id`). `certain` is false when the
27
+ * error may have been handled by a test the analysis does not read (`if (isNotFound(e)) return`),
28
+ * as the pack's own rules count it: they report only the certain ones.
29
+ */
30
+ export type ThrownClass = {
31
+ readonly id: string;
32
+ readonly certain: boolean;
33
+ /**
34
+ * Where the error is made, in the deepest function of the project the analysis follows it to:
35
+ * a `throw` (`kind: "throw"`), or a call of the platform or of a package that throws or rejects
36
+ * with it (`kind: "call"`). Absent when only a `@throws` tag names the class.
37
+ */
38
+ readonly origin?: ThrowOrigin;
39
+ };
40
+ /**
41
+ * `text`: for a call, the function it calls as written (`api.get`); absent for a `throw`.
42
+ * `platform`: the call is into the platform (TypeScript's lib, Node's types, the config's
43
+ * `platform`), not into a package or a declaration of the project.
44
+ */
45
+ export type ThrowOrigin = {
46
+ readonly kind: "throw";
47
+ readonly location: Location;
48
+ } | {
49
+ readonly kind: "call";
50
+ readonly location: Location;
51
+ readonly text: string;
52
+ /** Whether the call throws the error or returns a promise that rejects with it. */
53
+ readonly side: "throws" | "rejects";
54
+ readonly platform?: true;
55
+ };
56
+ /** A set of errors: the classes in it, and why the rest of it is unknown. */
57
+ export type ThrownErrors = {
58
+ /** Sorted by id. */
59
+ readonly classes: readonly ThrownClass[];
60
+ /** The places not followed, in file order: none when the set is exactly `classes`. */
61
+ readonly unknown: readonly ThrowsUnknown[];
62
+ /** Present when more places were not followed than `unknown` lists. */
63
+ readonly more?: true;
64
+ };
65
+ /** What calling one function can throw, and what the promise it returns can reject with. */
66
+ export type FunctionThrows = {
67
+ /** The function's name and where its name is. */
68
+ readonly name: string;
69
+ readonly location: Location;
70
+ readonly throws: ThrownErrors;
71
+ readonly rejects: ThrownErrors;
72
+ };
73
+ /**
74
+ * The analysis `errors/throws`: every named function of the project, by the symbol id of its
75
+ * declaration (`SymbolRef.id`, as `TypeQueries.symbolAt` gives it), sorted by id. A function's
76
+ * `@throws` tags, when it has them, are what it throws; otherwise its body is followed through
77
+ * the calls it makes, into other files and into packages.
78
+ */
79
+ export type ThrowsAnalysis = {
80
+ readonly functions: Readonly<Record<string, FunctionThrows>>;
81
+ /**
82
+ * Every class the functions name, and every class those extend, by id: so a reader can tell
83
+ * that a class extends another (`NotFound extends HttpException`).
84
+ */
85
+ readonly classes: Readonly<Record<string, ClassInfo>>;
86
+ };
87
+ /**
88
+ * A class of `ThrowsAnalysis.classes`: its name, the id of the class it extends (null for none),
89
+ * and `open` when what it extends cannot be followed (a mixin, a name that does not resolve, a
90
+ * class the summaries do not describe), so whether it is a subclass of another is not known.
91
+ */
92
+ export type ClassInfo = {
93
+ readonly name: string;
94
+ readonly parent: string | null;
95
+ readonly open: boolean;
96
+ /** The instance properties the class declares itself (`ClassFact.fields`); empty when not read. */
97
+ readonly fields: readonly string[];
98
+ /** With `open`: the parent's name as its declaration writes it, when it does not resolve. */
99
+ readonly declared?: string;
100
+ /** With `open`, for a package's class: the package's version that runs, when it is known. */
101
+ readonly version?: string;
102
+ /** With `open`, for a package's class: the `facts` key that names it (`ClassFact.key`). */
103
+ readonly key?: FactKey;
104
+ };
105
+ /** Solves the summaries into the published shape. */
106
+ export declare function throwsAnalysis(summaries: ReadonlyMap<string, Json>): ThrowsAnalysis;
107
+ /** `Plugin.analyses.throws` of the errors pack. */
108
+ export declare const throws: PluginAnalysis;
109
+ //# sourceMappingURL=analysis.d.ts.map
@@ -0,0 +1,170 @@
1
+ import { builtinName, builtinParent, isBuiltin } from "./builtins.js";
2
+ import { summarizeWithPackages } from "./project.js";
3
+ import { analyse } from "./solve.js";
4
+ function unknownOf(source) {
5
+ return {
6
+ location: { file: source.file, start: source.start, end: source.end },
7
+ text: source.text,
8
+ reason: source.reason,
9
+ ...(source.package === undefined ? {} : { package: source.package }),
10
+ ...(source.fact === undefined ? {} : { fact: source.fact }),
11
+ };
12
+ }
13
+ /** The function a call names, as written: `JSON.parse` for the leaf text `JSON.parse(…)`. */
14
+ function calledText(text) {
15
+ return text.endsWith("(…)") ? text.slice(0, -"(…)".length) : text;
16
+ }
17
+ /** The effects of a list and of everything nested in it (try bodies, catches, `finally`), in order. */
18
+ function* leaves(effects) {
19
+ for (const effect of effects) {
20
+ if (effect.k !== "try") {
21
+ yield effect;
22
+ continue;
23
+ }
24
+ yield* leaves(effect.body);
25
+ const { handler } = effect;
26
+ if (handler !== null) {
27
+ yield* leaves(handler.pre);
28
+ for (const branch of handler.branches)
29
+ yield* leaves(branch.body);
30
+ if (handler.otherwise !== null)
31
+ yield* leaves(handler.otherwise);
32
+ yield* leaves(handler.after);
33
+ }
34
+ yield* leaves(effect.fin);
35
+ }
36
+ }
37
+ /**
38
+ * Where a class a function throws is made, following the first call that brings it into the
39
+ * function it calls (`ThrownClass.origin`). Computed for the published analysis only: the solve's
40
+ * results hold no offsets, so an edit that only moves code does not re-solve the callers.
41
+ */
42
+ function originFinder(analysis) {
43
+ const memo = new Map();
44
+ const find = (fn, id, visiting) => {
45
+ const key = `${fn}\u0000${id}`;
46
+ const known = memo.get(key);
47
+ if (known !== undefined)
48
+ return known ?? undefined;
49
+ if (visiting.has(fn))
50
+ return undefined;
51
+ visiting.add(fn);
52
+ const entry = analysis.functions.get(fn);
53
+ let found;
54
+ for (const effect of leaves(entry === undefined ? [] : [...entry.fact.body, ...entry.fact.returns])) {
55
+ if (entry === undefined)
56
+ break;
57
+ const location = (at) => ({
58
+ file: entry.file,
59
+ start: at[0],
60
+ end: at[1],
61
+ });
62
+ if (effect.k === "class" && effect.id === id) {
63
+ // A class leaf with a call's text is a built-in call that throws it.
64
+ found =
65
+ effect.text === null
66
+ ? { kind: "throw", location: location(effect.at) }
67
+ : {
68
+ kind: "call",
69
+ location: location(effect.at),
70
+ text: calledText(effect.text),
71
+ side: "throws",
72
+ ...(effect.platform === true ? { platform: true } : {}),
73
+ };
74
+ }
75
+ else if (effect.k === "package" && effect.facts[effect.part].classes.includes(id)) {
76
+ found = {
77
+ kind: "call",
78
+ location: location(effect.at),
79
+ text: calledText(effect.text),
80
+ side: effect.part,
81
+ ...(effect.platform === true ? { platform: true } : {}),
82
+ };
83
+ }
84
+ else if (effect.k === "call") {
85
+ const result = analysis.results.get(effect.id);
86
+ const sides = effect.part === "both" ? [result?.throws, result?.rejects] : [result?.[effect.part]];
87
+ if (sides.some((side) => side?.classes.has(id) === true)) {
88
+ found = find(effect.id, id, visiting);
89
+ }
90
+ }
91
+ if (found !== undefined)
92
+ break;
93
+ }
94
+ visiting.delete(fn);
95
+ memo.set(key, found ?? null);
96
+ return found;
97
+ };
98
+ return (fn, id) => find(fn, id, new Set());
99
+ }
100
+ function errorsOf(set, origin) {
101
+ return {
102
+ classes: [...set.classes].map(([id, certain]) => {
103
+ const at = origin(id);
104
+ return at === undefined ? { id, certain } : { id, certain, origin: at };
105
+ }),
106
+ unknown: set.unknowns.map(unknownOf),
107
+ ...(set.more ? { more: true } : {}),
108
+ };
109
+ }
110
+ /** Solves the summaries into the published shape. */
111
+ export function throwsAnalysis(summaries) {
112
+ const analysis = analyse(summaries);
113
+ const originOf = originFinder(analysis);
114
+ const functions = {};
115
+ for (const id of [...analysis.results.keys()].sort()) {
116
+ const entry = analysis.functions.get(id);
117
+ const result = analysis.results.get(id);
118
+ if (entry === undefined || result === undefined)
119
+ continue;
120
+ functions[id] = {
121
+ name: entry.fact.name,
122
+ location: { file: entry.file, start: entry.fact.at[0], end: entry.fact.at[1] },
123
+ throws: errorsOf(result.throws, (one) => originOf(id, one)),
124
+ rejects: errorsOf(result.rejects, (one) => originOf(id, one)),
125
+ };
126
+ }
127
+ return { functions, classes: classesOf(functions, analysis.classes) };
128
+ }
129
+ /** What the analysis knows of a class id: a class of the platform, a summarized class, or neither. */
130
+ function classInfo(id, known) {
131
+ if (isBuiltin(id)) {
132
+ return { name: builtinName(id), parent: builtinParent(id), open: false, fields: [] };
133
+ }
134
+ const fact = known.get(id);
135
+ if (fact !== undefined) {
136
+ return {
137
+ name: fact.name,
138
+ parent: fact.parent,
139
+ open: fact.open,
140
+ fields: fact.fields,
141
+ ...(fact.declared === undefined ? {} : { declared: fact.declared }),
142
+ ...(fact.version === undefined ? {} : { version: fact.version }),
143
+ ...(fact.key === undefined ? {} : { key: fact.key }),
144
+ };
145
+ }
146
+ return { name: id.slice(id.lastIndexOf("#") + 1), parent: null, open: true, fields: [] };
147
+ }
148
+ /** Every class the functions name, with their ancestors, sorted by id. */
149
+ function classesOf(functions, known) {
150
+ const found = new Map();
151
+ const add = (start) => {
152
+ // A class that (wrongly) extends itself stops at the first id seen again.
153
+ for (let id = start; id !== null && !found.has(id);) {
154
+ const info = classInfo(id, known);
155
+ found.set(id, info);
156
+ id = info.parent;
157
+ }
158
+ };
159
+ for (const one of Object.values(functions)) {
160
+ for (const thrown of [...one.throws.classes, ...one.rejects.classes])
161
+ add(thrown.id);
162
+ }
163
+ return Object.fromEntries([...found].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
164
+ }
165
+ /** `Plugin.analyses.throws` of the errors pack. */
166
+ export const throws = {
167
+ summarize: (ctx) => summarizeWithPackages(ctx),
168
+ solve: throwsAnalysis,
169
+ };
170
+ //# sourceMappingURL=analysis.js.map
@@ -54,6 +54,4 @@ export declare const MAPPING_METHODS: ReadonlySet<string>;
54
54
  * the caller, so it is left out on purpose. Its own catches are still checked.
55
55
  */
56
56
  export declare const DEFERRED_CALLERS: ReadonlySet<string>;
57
- /** Whether a call into package `name`, written `callText`, is one of React's non-throwing hooks. */
58
- export declare function isNonThrowingReactHook(name: string, callText: string): boolean;
59
57
  //# sourceMappingURL=builtins.d.ts.map
@@ -163,37 +163,4 @@ export const DEFERRED_CALLERS = new Set([
163
163
  "IntersectionObserver",
164
164
  "PerformanceObserver",
165
165
  ]);
166
- /**
167
- * React's built-in hooks do not throw in correct use (misuse, like a hook called conditionally, is
168
- * a bug the rules-of-hooks lint finds, not part of their contract), so a call to one adds nothing.
169
- * Without this, every component would carry "unknown (package react)". `use()` is left out: it
170
- * rethrows a rejected promise.
171
- */
172
- const NON_THROWING_REACT_HOOKS = new Set([
173
- "useState",
174
- "useReducer",
175
- "useEffect",
176
- "useLayoutEffect",
177
- "useInsertionEffect",
178
- "useMemo",
179
- "useCallback",
180
- "useRef",
181
- "useContext",
182
- "useId",
183
- "useTransition",
184
- "useDeferredValue",
185
- "useImperativeHandle",
186
- "useDebugValue",
187
- "useSyncExternalStore",
188
- "useOptimistic",
189
- "useActionState",
190
- "useFormStatus",
191
- ]);
192
- /** Whether a call into package `name`, written `callText`, is one of React's non-throwing hooks. */
193
- export function isNonThrowingReactHook(name, callText) {
194
- if (name !== "react" && name !== "react-dom")
195
- return false;
196
- const callee = /([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(?/.exec(callText.split(".").pop() ?? "")?.[1];
197
- return callee !== undefined && NON_THROWING_REACT_HOOKS.has(callee);
198
- }
199
166
  //# sourceMappingURL=builtins.js.map
@@ -1,7 +1,18 @@
1
1
  import type { EditorContributions, Json, LibraryUse } from "@stateward/core";
2
2
  type LibraryFacts = NonNullable<EditorContributions["libraryFacts"]>;
3
- /** The rules whose summaries hold the throws facts; the first that ran is read. */
4
- export declare const FACT_RULES: readonly ["errors/throws-doc-mismatch"];
3
+ /**
4
+ * The analysis whose summaries hold the throws facts: the pack's rules, its editor contributions
5
+ * and other packs (through its solved value) all read this one copy.
6
+ */
7
+ export declare const THROWS_ANALYSIS = "errors/throws";
8
+ /**
9
+ * The throws facts of the last full check (`errors/throws`'s summaries), when one of the rules
10
+ * that show them ran; undefined otherwise. Another rule that reads the analysis (`must-handle-error`)
11
+ * does not turn the hover and hints on.
12
+ */
13
+ export declare function factSummaries(input: {
14
+ projectSummaries(ruleId: string): ReadonlyMap<string, Json> | undefined;
15
+ }): ReadonlyMap<string, Json> | undefined;
5
16
  /**
6
17
  * Every package function the project calls, with where its throws facts come from and why what
7
18
  * is unknown is unknown (`stateward deps`), from the last full check.
@@ -1,7 +1,25 @@
1
- import { TREE_RULES, throwsOf } from "../react/boundaries.js";
2
1
  import { readSummary } from "./summary.js";
3
- /** The rules whose summaries hold the throws facts; the first that ran is read. */
4
- export const FACT_RULES = ["errors/throws-doc-mismatch"];
2
+ /**
3
+ * The analysis whose summaries hold the throws facts: the pack's rules, its editor contributions
4
+ * and other packs (through its solved value) all read this one copy.
5
+ */
6
+ export const THROWS_ANALYSIS = "errors/throws";
7
+ /** The rules whose results the editor shows the throws facts for: when one of them ran. */
8
+ const FACT_RULES = [
9
+ "errors/throws-doc-mismatch",
10
+ "errors/render-throw-without-boundary",
11
+ "errors/catch-misses-error",
12
+ ];
13
+ /**
14
+ * The throws facts of the last full check (`errors/throws`'s summaries), when one of the rules
15
+ * that show them ran; undefined otherwise. Another rule that reads the analysis (`must-handle-error`)
16
+ * does not turn the hover and hints on.
17
+ */
18
+ export function factSummaries(input) {
19
+ return FACT_RULES.some((ruleId) => input.projectSummaries(ruleId) !== undefined)
20
+ ? input.projectSummaries(THROWS_ANALYSIS)
21
+ : undefined;
22
+ }
5
23
  function collect(effects, into) {
6
24
  for (const effect of effects) {
7
25
  if (effect.k === "package")
@@ -47,11 +65,11 @@ export function packagesCalled(summaries) {
47
65
  functions: new Map(),
48
66
  };
49
67
  byPackage.set(key, entry);
50
- const fn = entry.functions.get(facts.fn) ?? {
68
+ const fn = entry.functions.get(facts.key.name) ?? {
51
69
  source: facts.source,
52
70
  unknown: new Set(),
53
71
  };
54
- entry.functions.set(facts.fn, fn);
72
+ entry.functions.set(facts.key.name, fn);
55
73
  for (const reason of [...facts.throws.unknown, ...facts.rejects.unknown])
56
74
  fn.unknown.add(reason);
57
75
  }
@@ -66,14 +84,7 @@ export function packagesCalled(summaries) {
66
84
  }));
67
85
  }
68
86
  export const libraryFacts = (input) => {
69
- let summaries;
70
- for (const ruleId of FACT_RULES)
71
- summaries ??= input.projectSummaries(ruleId);
72
- for (const ruleId of TREE_RULES) {
73
- const trees = summaries === undefined ? input.projectSummaries(ruleId) : undefined;
74
- if (trees !== undefined)
75
- summaries = throwsOf(trees);
76
- }
87
+ const summaries = factSummaries(input);
77
88
  return summaries === undefined ? [] : packagesCalled(summaries);
78
89
  };
79
90
  //# sourceMappingURL=deps.js.map