@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
@@ -1,7 +1,11 @@
1
1
  import ts from "@stateward/core/typescript";
2
+ import { classIdOf, codeOnOneLine, declaredPackageOf, factKeyOf, isPlatformDeclaration, } from "@stateward/core";
2
3
  import { isFunctionBoundary, scanRunning, stripParentheses } from "../syntax.js";
3
- import { oneLine, shorten } from "../text.js";
4
- import { ANY_REJECTS, ARRAY_LENGTH, BUILTIN_ERRORS, DEFERRED_CALLERS, FETCH_ABORT, FETCH_REJECTS, MAPPING_METHODS, SYNC_CALLBACKS, THROWING_CONSTRUCTORS, THROWING_GLOBALS, THROWING_MEMBERS, builtinId, isNonThrowingReactHook, } from "./builtins.js";
4
+ import { shorten, shortenStart } from "../text.js";
5
+ import { cannotRun } from "./unreachable.js";
6
+ import { ANY_REJECTS, ARRAY_LENGTH, BUILTIN_ERRORS, DEFERRED_CALLERS, FETCH_ABORT, FETCH_REJECTS, MAPPING_METHODS, SYNC_CALLBACKS, THROWING_CONSTRUCTORS, THROWING_GLOBALS, REJECTING_MEMBERS, THROWING_MEMBERS, isBuiltin, } from "./builtins.js";
7
+ /** How many `const` names are followed to the error they hold (`const err = new X()`). */
8
+ const HELD_DEPTH = 3;
5
9
  /** Why something adds `unknown`, as the hover and the messages show it. */
6
10
  export const REASON = {
7
11
  noDeclaration: "no declaration",
@@ -12,6 +16,8 @@ export const REASON = {
12
16
  madeError: "an error made by a call",
13
17
  promise: "a promise that is not followed",
14
18
  heldPromise: "promise held in a variable",
19
+ accessor: "a getter or setter runs here",
20
+ untyped: "its type is `any`",
15
21
  };
16
22
  /** Why a callback handed to a call of the platform that is not in the tables adds `unknown`. */
17
23
  export function mayRunReason(callee) {
@@ -23,55 +29,28 @@ export const ANONYMOUS = "";
23
29
  const TEXT_MAX = 40;
24
30
  /** A class's `extends` chain is followed this deep at most. */
25
31
  const MAX_CLASS_DEPTH = 20;
26
- const TS_LIB = /\/typescript\/lib\/lib\.[^/]*\.d\.ts$/;
27
- /** A declaration of the platform: TypeScript's lib, or a global in a declaration file. */
28
- function isPlatform(node, file) {
29
- if (TS_LIB.test(file))
30
- return true;
31
- const sourceFile = node.getSourceFile();
32
- if (!sourceFile.isDeclarationFile)
33
- return false;
34
- const module = ts.findAncestor(node.parent, ts.isModuleDeclaration);
35
- const enclosing = module === undefined ? undefined : outermostModule(module);
36
- // `declare module "x"` is a package; `declare global` is the platform; a namespace is what
37
- // its file is.
38
- if (enclosing !== undefined && ts.isStringLiteral(enclosing.name))
39
- return false;
40
- if (enclosing?.name.text === "global")
41
- return true;
42
- return !ts.isExternalModule(sourceFile);
43
- }
44
- /** `axios`, `@tanstack/react-query`, `react` for `@types/react`. */
45
- function packageName(file) {
46
- const at = file.lastIndexOf("/node_modules/");
47
- const parts = (at < 0 ? file : file.slice(at + "/node_modules/".length)).split("/");
48
- const [first = "", second = ""] = parts;
49
- if (first === "@types")
50
- return second.includes("__") ? `@${second.replace("__", "/")}` : second;
51
- return first.startsWith("@") ? `${first}/${second}` : first;
52
- }
53
32
  /**
54
- * The package a declaration outside the project belongs to: by its node_modules folder, or, for a
55
- * package linked from elsewhere (a workspace package, whose real path has no node_modules), by
56
- * the name in its package.json.
33
+ * The id of the class a name refers to, and its declaration when the class is one the summaries
34
+ * describe (of the project or a package); a class of the platform has none.
57
35
  */
58
- export function packageNameOf(types, file) {
59
- return file.includes("/node_modules/")
60
- ? packageName(file)
61
- : (types.packageOf(file) ?? packageName(file));
62
- }
63
- /** The outermost of nested module declarations (`declare global { namespace X { … } }`). */
64
- function outermostModule(module) {
65
- const outer = ts.findAncestor(module.parent, ts.isModuleDeclaration);
66
- return outer === undefined ? module : outermostModule(outer);
67
- }
68
- /** The name of the `declare module "x"` a declaration sits in. */
69
- function ambientModuleName(node) {
70
- const module = ts.findAncestor(node.parent, ts.isModuleDeclaration);
71
- if (module === undefined)
36
+ function classIdAndDeclaration(types, node) {
37
+ const id = classIdOf(types, node);
38
+ if (id === undefined)
72
39
  return undefined;
73
- const outer = outermostModule(module);
74
- return ts.isStringLiteral(outer.name) ? outer.name.text : undefined;
40
+ const name = ts.isPropertyAccessExpression(node)
41
+ ? node.name
42
+ : ts.isQualifiedName(node)
43
+ ? node.right
44
+ : node;
45
+ const symbol = types.symbolAt(name);
46
+ const declaration = symbol === undefined ? undefined : types.declarationOf(symbol);
47
+ if (symbol === undefined || declaration === undefined)
48
+ return undefined;
49
+ // The platform's classes the analysis knows are its error classes; it describes none.
50
+ if (isBuiltin(id)) {
51
+ return BUILTIN_ERRORS.has(symbol.name) ? { id, symbol, declaration: undefined } : undefined;
52
+ }
53
+ return { id, symbol, declaration };
75
54
  }
76
55
  /**
77
56
  * `exports.load = function () {…}` (CommonJS, as a package's JavaScript writes it): the function
@@ -205,7 +184,14 @@ function calledName(callee) {
205
184
  return undefined;
206
185
  }
207
186
  function textOf(node, sourceFile) {
208
- return shorten(oneLine(node.getText(sourceFile)), TEXT_MAX);
187
+ return shorten(codeOnOneLine(node.getText(sourceFile)), TEXT_MAX);
188
+ }
189
+ /**
190
+ * The function a call or `new` names, as written, shortened from the start: each call of a chain
191
+ * keeps its own name (`…createQueryBuilder().delete`, `…delete().from`).
192
+ */
193
+ function calleeTextOf(callee, sourceFile) {
194
+ return shortenStart(codeOnOneLine(callee.getText(sourceFile)), TEXT_MAX);
209
195
  }
210
196
  function newScope(async, rejectParameters = new Set()) {
211
197
  return { async, returns: [], rejectParameters };
@@ -215,27 +201,17 @@ export function packageClassId(name, className) {
215
201
  return `package:${name}#${className}`;
216
202
  }
217
203
  /**
218
- * The id a class named in code has in the summaries (`builtin:TypeError`, `package:zod#ZodError`,
219
- * or the qualified id of a class of the project), without its facts; undefined when the name
220
- * resolves to nothing.
204
+ * The id `errors/throws` gives the error class a name refers to (core's `classIdOf`): undefined
205
+ * for a name of the platform that is not one of its error classes.
221
206
  */
222
- export function classIdOf(types, name) {
223
- const symbol = types.symbolAt(name);
224
- const declaration = symbol === undefined ? undefined : types.declarationOf(symbol);
225
- if (symbol === undefined || declaration === undefined)
226
- return undefined;
227
- if (types.isOwnFile(declaration.file))
228
- return symbol.id;
229
- if (isPlatform(declaration.node, declaration.file)) {
230
- return BUILTIN_ERRORS.has(symbol.name) ? builtinId(symbol.name) : undefined;
231
- }
232
- return packageClassId(ambientModuleName(declaration.node) ?? packageNameOf(types, declaration.file), symbol.name);
207
+ export function errorClassIdOf(types, name) {
208
+ return classIdAndDeclaration(types, name)?.id;
233
209
  }
234
210
  /**
235
- * The throws facts of the file (see summary.ts). With `packages`, a call into a package carries
236
- * its facts; without (a package's own source), it is unknown.
211
+ * The throws facts of the file (see summary.ts): a call into a package carries its facts
212
+ * (`packages`).
237
213
  */
238
- export function summarizeThrows(ctx, packages) {
214
+ export function summarizeThrows(ctx, quiet, packages) {
239
215
  const { sourceFile, types } = ctx;
240
216
  const classes = new Map();
241
217
  const spanOf = (node) => [node.getStart(sourceFile), node.getEnd()];
@@ -248,24 +224,12 @@ export function summarizeThrows(ctx, packages) {
248
224
  const held = new Map();
249
225
  // ---- classes --------------------------------------------------------------------------------
250
226
  const classRef = (node, depth = 0) => {
251
- const name = ts.isPropertyAccessExpression(node)
252
- ? node.name
253
- : ts.isQualifiedName(node)
254
- ? node.right
255
- : node;
256
- const symbol = types.symbolAt(name);
257
- const declaration = symbol === undefined ? undefined : types.declarationOf(symbol);
258
- if (symbol === undefined || declaration === undefined)
227
+ const found = classIdAndDeclaration(types, node);
228
+ if (found === undefined)
259
229
  return undefined;
260
- const own = types.isOwnFile(declaration.file);
261
- if (!own && isPlatform(declaration.node, declaration.file)) {
262
- return BUILTIN_ERRORS.has(symbol.name) ? builtinId(symbol.name) : undefined;
263
- }
264
- // A package's class is named by its package and name: its types, its source and the config
265
- // all name it so.
266
- const id = own
267
- ? symbol.id
268
- : packageClassId(ambientModuleName(declaration.node) ?? packageNameOf(types, declaration.file), symbol.name);
230
+ const { id, declaration, symbol } = found;
231
+ if (declaration === undefined)
232
+ return id;
269
233
  let classNode;
270
234
  if (ts.isClassDeclaration(declaration.node) || ts.isClassExpression(declaration.node)) {
271
235
  classNode = declaration.node;
@@ -280,20 +244,84 @@ export function summarizeThrows(ctx, packages) {
280
244
  return undefined;
281
245
  if (!classes.has(id)) {
282
246
  // Placeholder first: a class that (wrongly) extends itself stops here.
283
- classes.set(id, { id, name: symbol.name, parent: null, open: true });
247
+ classes.set(id, { id, name: symbol.name, parent: null, open: true, fields: [] });
284
248
  const base = classNode.heritageClauses
285
249
  ?.find((clause) => clause.token === ts.SyntaxKind.ExtendsKeyword)
286
250
  ?.types.at(0)?.expression;
287
251
  const parent = base === undefined || depth >= MAX_CLASS_DEPTH ? undefined : classRef(base, depth + 1);
252
+ const open = base !== undefined && parent === undefined;
253
+ const written = base === undefined ? undefined : writtenName(base);
254
+ // A package's class whose parent is not followed: the `facts` key a hint names it by.
255
+ const key = open && !types.isOwnFile(declaration.file)
256
+ ? factKeyOf(types, declaration, node)
257
+ : undefined;
288
258
  classes.set(id, {
289
259
  id,
290
260
  name: symbol.name,
291
261
  parent: parent ?? null,
292
- open: base !== undefined && parent === undefined,
262
+ open,
263
+ fields: fieldsOf(classNode),
264
+ ...(open && written !== undefined ? { declared: written } : {}),
265
+ ...(key === undefined ? {} : { key }),
293
266
  });
294
267
  }
295
268
  return id;
296
269
  };
270
+ /**
271
+ * A package's classes a call gives whose parents are not read yet (named only by a facts line,
272
+ * or extending what its source does not resolve): the parent its declarations state, so
273
+ * `EntityNotFoundError → TypeORMError → Error` is known without a facts line. A class whose
274
+ * declarations do not say stays open, with the package's version for the hint.
275
+ */
276
+ const declaredParents = (packageName, ids, facts) => {
277
+ const prefix = packageClassId(packageName, "");
278
+ const queue = [...ids];
279
+ const seen = new Set();
280
+ for (let id = queue.shift(); id !== undefined; id = queue.shift()) {
281
+ if (seen.has(id) || !id.startsWith(prefix))
282
+ continue;
283
+ seen.add(id);
284
+ const known = classes.get(id);
285
+ if (known !== undefined && !known.open) {
286
+ if (known.parent !== null)
287
+ queue.push(known.parent);
288
+ continue;
289
+ }
290
+ const name = known?.name ?? id.slice(prefix.length);
291
+ const declaration = types.exportedClassOf(packageName, name);
292
+ const declaredName = declaration !== undefined &&
293
+ (ts.isClassDeclaration(declaration.node) || ts.isClassExpression(declaration.node))
294
+ ? declaration.node.name
295
+ : undefined;
296
+ if (declaredName !== undefined && classIdOf(types, declaredName) === id) {
297
+ classes.delete(id);
298
+ const read = classRef(declaredName) === id ? classes.get(id) : undefined;
299
+ if (read !== undefined && !read.open) {
300
+ if (read.parent !== null)
301
+ queue.push(read.parent);
302
+ continue;
303
+ }
304
+ }
305
+ const now = classes.get(id);
306
+ const declared = now?.declared ?? known?.declared;
307
+ // Named from its declaration when there is one; with none, no key can name it.
308
+ const key = now?.key ??
309
+ known?.key ??
310
+ (declaration === undefined || declaredName === undefined
311
+ ? undefined
312
+ : factKeyOf(types, declaration, declaredName));
313
+ classes.set(id, {
314
+ id,
315
+ name,
316
+ parent: null,
317
+ open: true,
318
+ fields: now?.fields ?? known?.fields ?? [],
319
+ ...(declared === undefined ? {} : { declared }),
320
+ ...(facts.version === "" ? {} : { version: facts.version }),
321
+ ...(key === undefined ? {} : { key }),
322
+ });
323
+ }
324
+ };
297
325
  // ---- leaves ---------------------------------------------------------------------------------
298
326
  const unknownLeaf = (reason, text, node) => ({
299
327
  k: "unknown",
@@ -302,67 +330,102 @@ export function summarizeThrows(ctx, packages) {
302
330
  at: spanOf(node),
303
331
  });
304
332
  const classLeaves = (ids, text, node) => ids.map((id) => ({ k: "class", id, text, at: spanOf(node) }));
333
+ /** The classes a call into the platform throws (`new URL(…)`, `JSON.parse(…)`). */
334
+ const platformLeaves = (ids, text, node) => ids.map((id) => ({ k: "class", id, text, at: spanOf(node), platform: true }));
305
335
  /**
306
336
  * A call into a package, by its facts: what it throws where it is called (`sync`) and what its
307
- * promise rejects with. Undefined for one of React's hooks that throw nothing.
337
+ * promise rejects with. Undefined for a call the facts say throws nothing (`QuietCall`).
338
+ *
339
+ * The config's or a pack's `facts` for the function are taken as they are; without a line it is
340
+ * unknown. A `@throws` on its declaration is read only when the declaration is the project's own
341
+ * (same package as this file): a package's doc comments are not its contract (0041).
308
342
  */
309
343
  const packageLeaves = (resolved, text, node) => {
310
- if (isNonThrowingReactHook(resolved.name, text))
344
+ const target = ts.isPropertyAccessExpression(node) ? node.expression : undefined;
345
+ const call = {
346
+ ...resolved,
347
+ through: node,
348
+ ...(target === undefined
349
+ ? {}
350
+ : {
351
+ receiverClass: (names) => types.genericBaseOf(target, resolved.name, names)?.name,
352
+ }),
353
+ };
354
+ if (quiet(call))
311
355
  return undefined;
312
- // A declaration whose JSDoc was read (a project's own `.d.ts`): what its `@throws` says.
313
- const tagged = taggedLeaves(resolved.node, text, node);
314
- if (tagged !== undefined)
315
- return tagged;
316
- if (packages === undefined) {
317
- const leaf = unknownLeaf(`package ${resolved.name}`, text, node);
318
- return { sync: [leaf], promise: [leaf] };
356
+ // A declaration of the project's own (a `.d.ts`, a `declare module`): its tag is the
357
+ // developer's statement, taken as it is.
358
+ if (types.packageOf(resolved.file) === types.packageOf(sourceFile.fileName)) {
359
+ const doc = taggedOf(resolved.node, text, node);
360
+ if (doc !== undefined) {
361
+ const leaves = [...classLeaves(doc.classes, `${text}(…)`, node), ...doc.leaves];
362
+ return doc.promise ? { sync: [], promise: leaves } : { sync: leaves, promise: [] };
363
+ }
319
364
  }
320
- const found = packages(resolved);
365
+ const found = packages(call);
321
366
  for (const fact of found.classes)
322
367
  if (!classes.has(fact.id))
323
368
  classes.set(fact.id, fact);
324
- const at = spanOf(node);
325
369
  const { facts } = found;
370
+ declaredParents(resolved.name, [...facts.throws.classes, ...facts.rejects.classes], facts);
371
+ const at = spanOf(node);
326
372
  const side = (part) => facts[part].classes.length > 0 || facts[part].unknown.length > 0
327
- ? [{ k: "package", facts, part, text, at }]
373
+ ? [
374
+ {
375
+ k: "package",
376
+ facts,
377
+ part,
378
+ text,
379
+ at,
380
+ ...(resolved.platform ? { platform: true } : {}),
381
+ },
382
+ ]
328
383
  : [];
329
384
  return { sync: side("throws"), promise: side("rejects") };
330
385
  };
331
386
  /**
332
- * What a declaration without a body says it throws with `@throws` (on any of its overloads), as
333
- * leaves at the call; undefined without a tag. On a function that returns a promise the tag
334
- * is what the promise rejects with.
387
+ * What a declaration without a body says it throws with `@throws` (on any of its overloads):
388
+ * its classes, and a leaf at the call for each entry that names no class it finds or has no
389
+ * type. Undefined without a tag. On a function that returns a promise the tag is what the
390
+ * promise rejects with.
335
391
  */
336
- const taggedLeaves = (declaration, text, at) => {
392
+ const taggedOf = (declaration, text, at) => {
337
393
  const signatures = ts.isFunctionDeclaration(declaration) || ts.isMethodDeclaration(declaration)
338
394
  ? signaturesOf(declaration)
339
395
  : [];
340
- const doc = docOf(...(signatures.length > 0 ? signatures : [declaration]));
396
+ const doc = docOf(declaration, ...(signatures.length > 0 ? signatures : [declaration]));
341
397
  if (doc === null)
342
398
  return undefined;
343
399
  const span = spanOf(at);
344
- const leaves = [
345
- ...doc.entries.map((entry) => entry.id === null
346
- ? {
400
+ return {
401
+ promise: ts.isFunctionLike(declaration) && types.returnsPromiseLike(declaration),
402
+ classes: doc.entries.flatMap((entry) => (entry.id === null ? [] : [entry.id])),
403
+ leaves: [
404
+ ...doc.entries.flatMap((entry) => entry.id === null
405
+ ? [
406
+ {
407
+ k: "unknown",
408
+ reason: "`@throws` names a class that is not found",
409
+ text: entry.name,
410
+ at: span,
411
+ },
412
+ ]
413
+ : []),
414
+ ...doc.untyped.map(() => ({
347
415
  k: "unknown",
348
- reason: "`@throws` names a class that is not found",
349
- text: entry.name,
416
+ reason: "`@throws` without a type",
417
+ text: "@throws",
350
418
  at: span,
351
- }
352
- : { k: "class", id: entry.id, text: `${text}(…)`, at: span }),
353
- ...doc.untyped.map(() => ({
354
- k: "unknown",
355
- reason: "`@throws` without a type",
356
- text: "@throws",
357
- at: span,
358
- })),
359
- ];
360
- return ts.isFunctionLike(declaration) && types.returnsPromiseLike(declaration)
361
- ? { sync: [], promise: leaves }
362
- : { sync: leaves, promise: [] };
419
+ })),
420
+ ],
421
+ };
363
422
  };
364
423
  /** The leaf of a name that cannot be followed, by what it resolved to. */
365
424
  const unresolvedLeaf = (resolved, text, node) => {
425
+ // A callee typed `any` (an untyped `require`): no type states what it is, so no line can.
426
+ if ((resolved === undefined || resolved.kind === "other") && types.hasNoType(node)) {
427
+ return unknownLeaf(REASON.untyped, text, node);
428
+ }
366
429
  switch (resolved?.kind) {
367
430
  case undefined:
368
431
  return unknownLeaf(REASON.noDeclaration, text, node);
@@ -372,7 +435,7 @@ export function summarizeThrows(ctx, packages) {
372
435
  return unknownLeaf(REASON.callback, text, node);
373
436
  case "package":
374
437
  // Handled by `packageLeaves` where a call can be one.
375
- return isNonThrowingReactHook(resolved.name, text)
438
+ return quiet({ node: resolved.node, through: node })
376
439
  ? undefined
377
440
  : unknownLeaf(`package ${resolved.name}`, text, node);
378
441
  case "other":
@@ -421,6 +484,12 @@ export function summarizeThrows(ctx, packages) {
421
484
  return call(e, walk, false);
422
485
  if (ts.isNewExpression(e))
423
486
  return construct(e, walk);
487
+ if (ts.isPropertyAccessExpression(e) && runsAccessor(e)) {
488
+ // `box.value`, `box.value = 1`: a getter or setter of the project runs here.
489
+ expression(e.expression, walk);
490
+ walk.sink.push(unknownLeaf(REASON.accessor, textOf(e, sourceFile), e));
491
+ return [];
492
+ }
424
493
  if (ts.isConditionalExpression(e)) {
425
494
  expression(e.condition, walk);
426
495
  const branch = { ...walk, conditional: true };
@@ -431,6 +500,11 @@ export function summarizeThrows(ctx, packages) {
431
500
  });
432
501
  return [];
433
502
  };
503
+ /**
504
+ * Whether reading or writing the property may run a getter or setter with a body in the project:
505
+ * its own, or one a class gives for an interface's member the value may be.
506
+ */
507
+ const runsAccessor = (access) => types.readMayRunAccessor(access);
434
508
  /** What the `const` that `name` refers to holds, when it is one this file summarized. */
435
509
  const heldBy = (name) => {
436
510
  const symbol = types.symbolAt(name);
@@ -616,7 +690,7 @@ export function summarizeThrows(ctx, packages) {
616
690
  return [];
617
691
  }
618
692
  const name = calledName(callee);
619
- const text = textOf(callee, sourceFile);
693
+ const text = calleeTextOf(callee, sourceFile);
620
694
  if (name === undefined) {
621
695
  expression(callee, walk);
622
696
  evaluateArguments(node, walk);
@@ -627,6 +701,27 @@ export function summarizeThrows(ctx, packages) {
627
701
  const receiver = ts.isPropertyAccessExpression(callee) ? callee.expression : undefined;
628
702
  const resolved = resolve(name);
629
703
  const args = node.arguments;
704
+ if (resolved?.kind === "platform" &&
705
+ receiver !== undefined &&
706
+ (resolved.name === "call" || resolved.name === "apply") &&
707
+ (resolved.owner === "Function" || resolved.owner === "CallableFunction")) {
708
+ // `failB.call(null)`, `failB.apply(null, [])`: the function itself runs.
709
+ const target = calledName(stripParentheses(receiver));
710
+ const runs = target === undefined ? undefined : resolve(target);
711
+ evaluateArguments(node, walk);
712
+ const shown = textOf(receiver, sourceFile);
713
+ if (runs?.kind === "function") {
714
+ if (runs.generator)
715
+ return [];
716
+ const at = spanOf(receiver);
717
+ if (!runs.async)
718
+ walk.sink.push({ k: "call", id: runs.id, part: "throws", text: shown, at });
719
+ return [{ k: "call", id: runs.id, part: "rejects", text: shown, at }];
720
+ }
721
+ const leaf = unknownLeaf(REASON.dynamic, text, callee);
722
+ walk.sink.push(leaf);
723
+ return [leaf];
724
+ }
630
725
  if (resolved?.kind === "platform") {
631
726
  const key = resolved.owner === null ? resolved.name : `${resolved.owner}.${resolved.name}`;
632
727
  if (resolved.owner === "Promise") {
@@ -660,7 +755,7 @@ export function summarizeThrows(ctx, packages) {
660
755
  return [];
661
756
  case "any":
662
757
  elements(first, walk);
663
- return classLeaves([ANY_REJECTS], `${text}(…)`, node);
758
+ return platformLeaves([ANY_REJECTS], `${text}(…)`, node);
664
759
  case "reject":
665
760
  return first === undefined ? [] : thrown(first, walk);
666
761
  case "resolve":
@@ -691,13 +786,19 @@ export function summarizeThrows(ctx, packages) {
691
786
  }
692
787
  }
693
788
  if (key === "fetch") {
694
- return classLeaves(signalOf(args[1]) ? [...FETCH_REJECTS, FETCH_ABORT] : FETCH_REJECTS, `${text}(…)`, node);
789
+ return platformLeaves(signalOf(args[1]) ? [...FETCH_REJECTS, FETCH_ABORT] : FETCH_REJECTS, `${text}(…)`, node);
695
790
  }
791
+ const rejects = REJECTING_MEMBERS.get(key);
792
+ if (rejects !== undefined)
793
+ return platformLeaves(rejects, `${text}(…)`, node);
696
794
  const throws = resolved.owner === null
697
795
  ? (THROWING_GLOBALS.get(key) ??
698
796
  (key === "Array" && args.length === 1 ? ARRAY_LENGTH : []))
699
- : (THROWING_MEMBERS.get(key) ?? []);
700
- walk.sink.push(...classLeaves(throws, `${text}(…)`, node));
797
+ : // `n.toString()` with no radix cannot throw; with one, it may.
798
+ key === "Number.toString" && args.length === 0
799
+ ? []
800
+ : (THROWING_MEMBERS.get(key) ?? []);
801
+ walk.sink.push(...platformLeaves(throws, `${text}(…)`, node));
701
802
  return mapping && MAPPING_METHODS.has(key) ? mapped : [];
702
803
  }
703
804
  if (receiver !== undefined)
@@ -762,7 +863,7 @@ export function summarizeThrows(ctx, packages) {
762
863
  const construct = (node, walk) => {
763
864
  const callee = stripParentheses(node.expression);
764
865
  const name = calledName(callee);
765
- const text = textOf(callee, sourceFile);
866
+ const text = calleeTextOf(callee, sourceFile);
766
867
  const args = node.arguments ?? [];
767
868
  if (name === undefined) {
768
869
  expression(callee, walk);
@@ -789,7 +890,7 @@ export function summarizeThrows(ctx, packages) {
789
890
  ? []
790
891
  : (THROWING_CONSTRUCTORS.get(resolved.name) ??
791
892
  (resolved.name === "Array" && args.length === 1 ? ARRAY_LENGTH : []));
792
- walk.sink.push(...classLeaves(throws, `new ${text}(…)`, node));
893
+ walk.sink.push(...platformLeaves(throws, `new ${text}(…)`, node));
793
894
  if (!DEFERRED_CALLERS.has(resolved.name)) {
794
895
  walk.sink.push(...mayRun(args, `new ${text}`, callee, walk));
795
896
  }
@@ -837,9 +938,49 @@ export function summarizeThrows(ctx, packages) {
837
938
  ? node.getStart(sourceFile)
838
939
  : undefined;
839
940
  };
941
+ /** `Object.assign(target, …)`: it returns `target`. */
942
+ const isObjectAssign = (call) => {
943
+ const callee = stripParentheses(call.expression);
944
+ return (ts.isPropertyAccessExpression(callee) &&
945
+ ts.isIdentifier(callee.expression) &&
946
+ callee.expression.text === "Object" &&
947
+ callee.name.text === "assign");
948
+ };
949
+ /**
950
+ * The class of the error a value is, when the code makes it in plain sight: `new X(…)`,
951
+ * `Object.assign(new X(), …)`, or a `const` holding one (`const err = new X(); throw err`).
952
+ */
953
+ const madeClass = (value, depth) => {
954
+ const e = unwrap(value);
955
+ if (ts.isNewExpression(e))
956
+ return classRef(stripParentheses(e.expression));
957
+ if (ts.isCallExpression(e) && isObjectAssign(e)) {
958
+ const [target] = e.arguments;
959
+ return target === undefined ? undefined : madeClass(target, depth);
960
+ }
961
+ if (!ts.isIdentifier(e) || depth >= HELD_DEPTH)
962
+ return undefined;
963
+ const symbol = types.symbolAt(e);
964
+ const node = symbol === undefined ? undefined : types.declarationOf(symbol)?.node;
965
+ if (node === undefined ||
966
+ !ts.isVariableDeclaration(node) ||
967
+ node.initializer === undefined ||
968
+ !ts.isVariableDeclarationList(node.parent) ||
969
+ (node.parent.flags & ts.NodeFlags.Const) === 0) {
970
+ return undefined;
971
+ }
972
+ return madeClass(node.initializer, depth + 1);
973
+ };
840
974
  /** What `throw <value>` (or `reject(value)`) throws; its own calls go to the sink. */
841
975
  const thrown = (value, walk) => {
842
976
  const e = stripParentheses(value);
977
+ if (ts.isCallExpression(e) && isObjectAssign(e)) {
978
+ const id = madeClass(e, 0);
979
+ if (id !== undefined) {
980
+ evaluateArguments(e, walk);
981
+ return [{ k: "class", id, text: null, at: spanOf(e) }];
982
+ }
983
+ }
843
984
  if (ts.isNewExpression(e) || ts.isCallExpression(e)) {
844
985
  const id = classRef(stripParentheses(e.expression));
845
986
  if (id !== undefined) {
@@ -857,6 +998,9 @@ export function summarizeThrows(ctx, packages) {
857
998
  const of = caughtVariable(e);
858
999
  if (of !== undefined)
859
1000
  return [{ k: "rethrow", of, maybe: walk.conditional, at: spanOf(e) }];
1001
+ const id = madeClass(e, 0);
1002
+ if (id !== undefined)
1003
+ return [{ k: "class", id, text: null, at: spanOf(e) }];
860
1004
  }
861
1005
  expression(e, walk);
862
1006
  return [unknownLeaf(REASON.thrownValue, `throw ${textOf(e, sourceFile)}`, e)];
@@ -881,7 +1025,9 @@ export function summarizeThrows(ctx, packages) {
881
1025
  walk.sink.push(tryOf(node, walk.scope));
882
1026
  }
883
1027
  else if (ts.isThrowStatement(node)) {
884
- walk.sink.push(...thrown(node.expression, walk));
1028
+ // A `throw` no value can reach (an exhaustive switch's `default`) throws nothing.
1029
+ if (!cannotRun(types, node))
1030
+ walk.sink.push(...thrown(node.expression, walk));
885
1031
  }
886
1032
  else if (ts.isReturnStatement(node)) {
887
1033
  if (node.expression !== undefined) {
@@ -1145,7 +1291,7 @@ export function summarizeThrows(ctx, packages) {
1145
1291
  return plain();
1146
1292
  };
1147
1293
  // ---- @throws --------------------------------------------------------------------------------
1148
- const docOf = (...nodes) => {
1294
+ const docOf = (declared, ...nodes) => {
1149
1295
  const tags = new Set(nodes.flatMap((node) => ts.getJSDocTags(node)));
1150
1296
  const entries = [];
1151
1297
  const untyped = [];
@@ -1162,7 +1308,7 @@ export function summarizeThrows(ctx, packages) {
1162
1308
  const id = ts.isTypeReferenceNode(type) ? classRef(type.typeName) : undefined;
1163
1309
  entries.push({
1164
1310
  id: id ?? null,
1165
- name: shorten(oneLine(type.getText(sourceFile)), TEXT_MAX),
1311
+ name: shorten(codeOnOneLine(type.getText(sourceFile)), TEXT_MAX),
1166
1312
  at: spanOf(type),
1167
1313
  });
1168
1314
  }
@@ -1177,7 +1323,10 @@ export function summarizeThrows(ctx, packages) {
1177
1323
  else
1178
1324
  add(type);
1179
1325
  }
1180
- return found ? { entries, untyped } : null;
1326
+ const start = ts.isPropertyDeclaration(declared) || ts.isPropertyAssignment(declared)
1327
+ ? declared.name.getStart()
1328
+ : declared.getStart();
1329
+ return found ? { entries, untyped, declared: start } : null;
1181
1330
  };
1182
1331
  // ---- functions ------------------------------------------------------------------------------
1183
1332
  const functions = [];
@@ -1197,7 +1346,7 @@ export function summarizeThrows(ctx, packages) {
1197
1346
  statement(body, walk);
1198
1347
  else
1199
1348
  scope.returns.push(...flowing(body, walk));
1200
- const doc = name === undefined ? null : docOf(declaration, fn);
1349
+ const doc = name === undefined ? null : docOf(declaration, declaration, fn);
1201
1350
  functions.push({
1202
1351
  id: symbol.id,
1203
1352
  name: symbol.name,
@@ -1219,7 +1368,7 @@ export function summarizeThrows(ctx, packages) {
1219
1368
  */
1220
1369
  const bodylessFact = (name, node) => {
1221
1370
  const symbol = types.symbolAt(name);
1222
- const doc = docOf(...signaturesOf(node));
1371
+ const doc = docOf(node, ...signaturesOf(node));
1223
1372
  if (symbol === undefined || doc === null)
1224
1373
  return;
1225
1374
  functions.push({
@@ -1303,7 +1452,10 @@ function resolveWith(types, name) {
1303
1452
  return undefined;
1304
1453
  const node = declaration.node;
1305
1454
  if (!types.isOwnFile(declaration.file)) {
1306
- if (isPlatform(node, declaration.file)) {
1455
+ // `declare module "x";` gives every import `any`: no type states anything, so no declaration.
1456
+ if (ts.isModuleDeclaration(node) && node.body === undefined)
1457
+ return undefined;
1458
+ if (isPlatformDeclaration(node, declaration.file)) {
1307
1459
  const parent = node.parent;
1308
1460
  const owner = (ts.isMethodSignature(node) || ts.isPropertySignature(node)) &&
1309
1461
  ts.isInterfaceDeclaration(parent)
@@ -1311,14 +1463,66 @@ function resolveWith(types, name) {
1311
1463
  : null;
1312
1464
  return { kind: "platform", owner, name: symbol.name };
1313
1465
  }
1466
+ // Outside the project and of no package stateward can name: as a name with no declaration.
1467
+ const packageName = declaredPackageOf(types, declaration);
1468
+ if (packageName === undefined)
1469
+ return undefined;
1314
1470
  return {
1315
1471
  kind: "package",
1316
- name: ambientModuleName(node) ?? packageNameOf(types, declaration.file),
1472
+ name: packageName,
1317
1473
  id: symbol.id,
1318
1474
  node,
1319
1475
  file: declaration.file,
1476
+ platform: types.isPlatformName(name),
1320
1477
  };
1321
1478
  }
1322
1479
  return ownKind(node, symbol.id);
1323
1480
  }
1481
+ /**
1482
+ * The instance properties a class declares itself, sorted: property declarations (not static),
1483
+ * parameter properties, and `this.x = …` statements of its constructor.
1484
+ */
1485
+ /** The name an `extends` expression ends in (`TypeORMError_1.TypeORMError`), else undefined. */
1486
+ function writtenName(base) {
1487
+ const value = stripParentheses(base);
1488
+ if (ts.isIdentifier(value))
1489
+ return value.text;
1490
+ return ts.isPropertyAccessExpression(value) ? value.name.text : undefined;
1491
+ }
1492
+ function fieldsOf(node) {
1493
+ const names = new Set();
1494
+ const isStatic = (member) => (ts.getCombinedModifierFlags(member) & ts.ModifierFlags.Static) !== 0;
1495
+ for (const member of node.members) {
1496
+ if (ts.isPropertyDeclaration(member) && !isStatic(member)) {
1497
+ const name = memberName(member.name);
1498
+ if (name !== undefined)
1499
+ names.add(name);
1500
+ }
1501
+ if (ts.isConstructorDeclaration(member)) {
1502
+ for (const parameter of member.parameters) {
1503
+ if (ts.isParameterPropertyDeclaration(parameter, member) &&
1504
+ ts.isIdentifier(parameter.name)) {
1505
+ names.add(parameter.name.text);
1506
+ }
1507
+ }
1508
+ for (const statement of member.body?.statements ?? []) {
1509
+ if (!ts.isExpressionStatement(statement))
1510
+ continue;
1511
+ const expression = statement.expression;
1512
+ if (ts.isBinaryExpression(expression) &&
1513
+ expression.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
1514
+ ts.isPropertyAccessExpression(expression.left) &&
1515
+ expression.left.expression.kind === ts.SyntaxKind.ThisKeyword) {
1516
+ names.add(expression.left.name.text);
1517
+ }
1518
+ }
1519
+ }
1520
+ }
1521
+ return [...names].sort();
1522
+ }
1523
+ function memberName(name) {
1524
+ if (ts.isIdentifier(name) || ts.isPrivateIdentifier(name))
1525
+ return name.text;
1526
+ return ts.isStringLiteral(name) || ts.isNumericLiteral(name) ? name.text : undefined;
1527
+ }
1324
1528
  //# sourceMappingURL=summarize.js.map