@stateward/core 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 (75) hide show
  1. package/dist/analyses.d.ts +37 -0
  2. package/dist/analyses.js +57 -0
  3. package/dist/backend/program-record.d.ts +7 -0
  4. package/dist/backend/typescript6.d.ts +35 -32
  5. package/dist/backend/typescript6.js +3804 -163
  6. package/dist/baseline.d.ts +1 -1
  7. package/dist/baseline.js +14 -10
  8. package/dist/cache.d.ts +89 -5
  9. package/dist/cache.js +271 -40
  10. package/dist/checker.d.ts +11 -1
  11. package/dist/checker.js +32 -2
  12. package/dist/class-id.d.ts +34 -0
  13. package/dist/class-id.js +93 -0
  14. package/dist/code-text.d.ts +8 -0
  15. package/dist/code-text.js +66 -0
  16. package/dist/config-file.js +7 -5
  17. package/dist/config.d.ts +10 -2
  18. package/dist/config.js +541 -49
  19. package/dist/define.d.ts +8 -2
  20. package/dist/disk-cache.d.ts +2 -0
  21. package/dist/disk-cache.js +77 -11
  22. package/dist/engine.d.ts +51 -1
  23. package/dist/engine.js +517 -42
  24. package/dist/fact-lines.d.ts +31 -0
  25. package/dist/fact-lines.js +197 -0
  26. package/dist/facts-versions.d.ts +27 -0
  27. package/dist/facts-versions.js +99 -0
  28. package/dist/fixes.js +9 -4
  29. package/dist/guarantees.d.ts +63 -11
  30. package/dist/guarantees.js +151 -21
  31. package/dist/ignores.d.ts +11 -0
  32. package/dist/ignores.js +74 -27
  33. package/dist/implementation.d.ts +0 -6
  34. package/dist/implementation.js +0 -17
  35. package/dist/index.d.ts +10 -9
  36. package/dist/index.js +14 -7
  37. package/dist/internal.d.ts +9 -5
  38. package/dist/internal.js +6 -3
  39. package/dist/lazy.d.ts +8 -1
  40. package/dist/lazy.js +27 -2
  41. package/dist/ledger.d.ts +77 -0
  42. package/dist/ledger.js +423 -0
  43. package/dist/off-by-default.d.ts +13 -0
  44. package/dist/off-by-default.js +15 -0
  45. package/dist/options.d.ts +21 -5
  46. package/dist/options.js +22 -7
  47. package/dist/package-facts.d.ts +211 -17
  48. package/dist/package-facts.js +520 -38
  49. package/dist/plan.d.ts +1 -1
  50. package/dist/plan.js +7 -2
  51. package/dist/release.d.ts +12 -21
  52. package/dist/release.js +28 -38
  53. package/dist/renamed.d.ts +22 -3
  54. package/dist/renamed.js +50 -16
  55. package/dist/rollout.js +7 -4
  56. package/dist/safe-calls.d.ts +26 -0
  57. package/dist/safe-calls.js +345 -0
  58. package/dist/severity.d.ts +1 -1
  59. package/dist/severity.js +17 -3
  60. package/dist/stated.d.ts +37 -0
  61. package/dist/stated.js +123 -0
  62. package/dist/test-runner.d.ts +18 -0
  63. package/dist/test-runner.js +483 -0
  64. package/dist/testing-tsc.d.ts +16 -0
  65. package/dist/testing-tsc.js +86 -0
  66. package/dist/testing.d.ts +5 -4
  67. package/dist/testing.js +6 -6
  68. package/dist/timing.d.ts +15 -0
  69. package/dist/timing.js +41 -2
  70. package/dist/types.d.ts +1068 -16
  71. package/dist/unread.d.ts +90 -0
  72. package/dist/unread.js +405 -0
  73. package/dist/vocabulary.d.ts +1 -1
  74. package/dist/vocabulary.js +1 -1
  75. package/package.json +4 -2
@@ -1,9 +1,38 @@
1
1
  /**
2
2
  * The `facts` line for a package function or property: the config's first, then the facts the
3
- * loaded plugins ship. Core reads the lines and knows no library; each line names a declaration
4
- * by its path in the package's types (`Observable.subscribe`) or by its own name (`onSnapshot`).
3
+ * loaded plugins ship. Core reads the lines and knows no library. A line's key is a name as
4
+ * written from a module (`"typeorm": { "Repository.find": … }`), which the type checker resolves
5
+ * to a symbol; a declaration has the line whose key resolves to it (0041).
5
6
  */
7
+ import { createHash } from "node:crypto";
6
8
  import ts from "typescript";
9
+ import { codeOnOneLine } from "./code-text.js";
10
+ import { packageVersionOf, unread, unreadFinding } from "./unread.js";
11
+ /** The nodes each file context has reported a left-out facts line at, so each is said once. */
12
+ const reportedWithheld = new WeakMap();
13
+ /**
14
+ * Reports, once per node, a lookup that found a facts line left out for the version the project
15
+ * runs (`Unread` from `packageFactOf` and the lookups built on it): "not checked: <what>: <reason>",
16
+ * with the line's hint. A rule then reads the call as it would with no line.
17
+ */
18
+ export function reportWithheld(ctx, found, node, what) {
19
+ let seen = reportedWithheld.get(ctx);
20
+ if (seen === undefined) {
21
+ seen = new WeakSet();
22
+ reportedWithheld.set(ctx, seen);
23
+ }
24
+ if (seen.has(node))
25
+ return;
26
+ seen.add(node);
27
+ ctx.unknown({ ...unreadFinding(found, { what, hint: found.hint ?? "" }), node });
28
+ }
29
+ /** The `Unread` a line left out for the project's version gives: its reason and hint. */
30
+ function withheldUnread(left) {
31
+ return unread(left.reason, { hint: left.hint });
32
+ }
33
+ function states(fact, wanted) {
34
+ return wanted === undefined || fact[wanted] !== undefined;
35
+ }
7
36
  function unwrapped(expression) {
8
37
  let node = expression;
9
38
  while (ts.isParenthesizedExpression(node) ||
@@ -49,9 +78,28 @@ export function calleeName(call) {
49
78
  return callee.name;
50
79
  return undefined;
51
80
  }
52
- /** The module a file imports a name from: `"firebase/firestore"` for `onSnapshot`. */
81
+ /**
82
+ * `declared` with the value `name` is read on (`store` in `store.find`) as its receiver; as it is
83
+ * for a bare name.
84
+ */
85
+ export function withReceiverOf(declared, name) {
86
+ const parent = name.parent;
87
+ return ts.isPropertyAccessExpression(parent) && parent.name === name
88
+ ? { ...declared, receiver: parent.expression }
89
+ : declared;
90
+ }
91
+ /**
92
+ * The module a file imports a name from: `"firebase/firestore"` for `onSnapshot`, also through
93
+ * `import name = require("…")`.
94
+ */
53
95
  export function importedFrom(sourceFile, name) {
54
96
  for (const statement of sourceFile.statements) {
97
+ if (ts.isImportEqualsDeclaration(statement) &&
98
+ statement.name.text === name &&
99
+ ts.isExternalModuleReference(statement.moduleReference) &&
100
+ ts.isStringLiteral(statement.moduleReference.expression)) {
101
+ return statement.moduleReference.expression.text;
102
+ }
55
103
  if (!ts.isImportDeclaration(statement) || !ts.isStringLiteral(statement.moduleSpecifier)) {
56
104
  continue;
57
105
  }
@@ -81,39 +129,246 @@ export function rootName(expression) {
81
129
  return rootName(node.expression);
82
130
  return undefined;
83
131
  }
84
- function factOf(facts, packages, path) {
85
- for (const name of packages) {
86
- const functions = facts[name];
87
- if (functions === undefined)
88
- continue;
89
- const fact = functions[path.join(".")] ?? functions[path.at(-1) ?? ""];
90
- if (fact !== undefined)
91
- return { package: name, fact };
132
+ /** The name of the package a module path is in: `@acme/kit` of `@acme/kit/lib/x`. */
133
+ export function packageOfModule(module) {
134
+ const parts = module.split("/");
135
+ return module.startsWith("@") ? parts.slice(0, 2).join("/") : (parts[0] ?? module);
136
+ }
137
+ /**
138
+ * The class a written `facts` line leaves for the developer to name (`throws: ["ErrorClass"]`): the
139
+ * config warns of it until it is replaced.
140
+ */
141
+ export const PLACEHOLDER_CLASS = "ErrorClass";
142
+ /** The kinds a `facts` line states of a call's errors, in the order a line writes them. */
143
+ const FACT_SIDES = ["throws", "rejects"];
144
+ /**
145
+ * The kinds a `facts` line states for calls that need `sides`, once each, `throws` first. Kinds are
146
+ * strict: `throws` states a synchronous throw, `rejects` a promise's rejection, so a line for a
147
+ * class whose methods need both carries both.
148
+ */
149
+ export function neededSides(sides) {
150
+ return FACT_SIDES.filter((side) => sides.includes(side));
151
+ }
152
+ /** A key's name that stands for every name one step below: `"*"`, `"Repository.*"`. */
153
+ export const WILDCARD = "*";
154
+ export function factGrainOf(name) {
155
+ if (name === WILDCARD)
156
+ return { kind: "package" };
157
+ const suffix = `.${WILDCARD}`;
158
+ return name.endsWith(suffix) && name.length > suffix.length
159
+ ? { kind: "class", owner: name.slice(0, -suffix.length) }
160
+ : { kind: "function" };
161
+ }
162
+ /** The more specific grain wins: a function's line over its class's, a class's over its package's. */
163
+ const GRAIN_RANK = {
164
+ function: 0,
165
+ class: 1,
166
+ package: 2,
167
+ };
168
+ /**
169
+ * Whether a key's target states a call of `declaration` made through `receiver` (`store` in
170
+ * `store.find()`; undefined when the call has none, or the caller does not know it): a declaration
171
+ * it names on any call, or one a class inherits, called on a value of that class
172
+ * (`FactTarget.throughReceiver`).
173
+ */
174
+ function targetStates(types, target, declaration, receiver) {
175
+ if (target.kind !== "found")
176
+ return false;
177
+ if (target.declarations.has(declaration))
178
+ return true;
179
+ const classes = target.throughReceiver.get(declaration);
180
+ return classes !== undefined && receiver !== undefined && types.isOrExtends(receiver, classes);
181
+ }
182
+ /**
183
+ * The line of `facts` whose key resolves to `declaration` (`TypeQueries.factTarget`): its module,
184
+ * its name and the line. The most specific grain wins (`factGrainOf`): a function's line, then a
185
+ * class's (`"Repository.*"`), then a package's (`"*"`); the line chosen replaces the coarser ones
186
+ * whole. Among keys of one grain, the first the table lists. A class line states a method the
187
+ * class inherits only through `receiver`, the value it is called on, when that is of the class.
188
+ */
189
+ export function factLineOf(types, facts, declaration, receiver) {
190
+ let best;
191
+ for (const [module, functions] of Object.entries(facts)) {
192
+ for (const [name, fact] of Object.entries(functions)) {
193
+ const rank = GRAIN_RANK[factGrainOf(name).kind];
194
+ if (best !== undefined && best.rank <= rank)
195
+ continue;
196
+ if (targetStates(types, types.factTarget(module, name), declaration, receiver)) {
197
+ if (rank === GRAIN_RANK.function)
198
+ return { package: module, name, fact };
199
+ best = { package: module, name, fact, rank };
200
+ }
201
+ }
92
202
  }
93
- return undefined;
203
+ return best === undefined
204
+ ? undefined
205
+ : { package: best.package, name: best.name, fact: best.fact };
206
+ }
207
+ /**
208
+ * The facts line for a package's declaration from the config's `facts`. `Unread` when the
209
+ * config's line is left out for the version the project runs (`"@versions"`) and states `wanted`;
210
+ * undefined when no line names it.
211
+ */
212
+ export function declarationFactOf(ctx, declared, wanted) {
213
+ const found = factLineOf(ctx.types, ctx.facts, declared.node, declared.receiver);
214
+ if (found !== undefined)
215
+ return { kind: "fact", ...found, source: "config" };
216
+ const left = withheldFactOf(ctx.withheldFacts, ctx.types, declared, "config", wanted);
217
+ return left === undefined ? undefined : withheldUnread(left);
94
218
  }
95
219
  /**
96
- * The facts line for `declared`, a declaration in a package's types, reached in the file through
97
- * `through` (the callee or the object a property is read from, whose import names the package):
98
- * the config's line when it has one for the declaration, else a shipped one. Undefined for a
99
- * declaration of the project, or one no line names.
220
+ * The facts left out for a file's project version (`FileContext.withheldFacts`) that would name a
221
+ * declaration, as `factLineOf` finds a line, from `source` when given and stating `wanted` when
222
+ * given: the call it names is then "not checked" with their reason. Undefined when none would.
100
223
  */
101
- export function packageFactOf(declared, through, ctx) {
224
+ export function withheldFactOf(withheld, types, declared, source, wanted) {
225
+ return withheld.find((left) => {
226
+ if (source !== undefined && left.source !== source)
227
+ return false;
228
+ const table = { [left.package]: left.functions };
229
+ const found = factLineOf(types, table, declared.node, declared.receiver);
230
+ return found !== undefined && states(found.fact, wanted);
231
+ });
232
+ }
233
+ /**
234
+ * The facts line for `declared`, a declaration in a package's types: the config's line when one
235
+ * resolves to it, else a shipped one. Undefined for a declaration of the project, or one no line
236
+ * names.
237
+ */
238
+ export function packageFactOf(declared, ctx, wanted) {
102
239
  const { types } = ctx;
103
240
  if (types.isOwnFile(declared.file))
104
241
  return undefined;
105
- const root = through === undefined ? undefined : rootName(through);
106
- const specifier = root === undefined ? undefined : importedFrom(ctx.sourceFile, root);
107
- const owner = types.packageOf(declared.file);
108
- const packages = [
109
- ...new Set([specifier, owner].filter((item) => item !== undefined)),
110
- ];
111
- const path = pathOf(declared.node);
112
- const fromConfig = factOf(ctx.facts, packages, path);
242
+ const fromConfig = factLineOf(types, ctx.facts, declared.node, declared.receiver);
113
243
  if (fromConfig !== undefined)
114
- return { ...fromConfig, source: "config" };
115
- const shipped = factOf(ctx.shippedFacts, packages, path);
116
- return shipped === undefined ? undefined : { ...shipped, source: "shipped" };
244
+ return { kind: "fact", ...fromConfig, source: "config" };
245
+ // A line left out for the project's version: "not checked", never read as another version's.
246
+ const left = (source) => {
247
+ const found = withheldFactOf(ctx.withheldFacts, types, declared, source, wanted);
248
+ return found === undefined ? undefined : withheldUnread(found);
249
+ };
250
+ const ownLeft = left("config");
251
+ if (ownLeft !== undefined)
252
+ return ownLeft;
253
+ const shipped = factLineOf(types, ctx.shippedFacts, declared.node, declared.receiver);
254
+ return shipped === undefined ? left("shipped") : { kind: "fact", ...shipped, source: "shipped" };
255
+ }
256
+ /**
257
+ * Why no `facts` key can name a call (`FactKey` `unnamed`): by the module the call is imported
258
+ * from, when it is; else by the modules of its package.
259
+ */
260
+ export function unnamedReason(found) {
261
+ return found.through === undefined
262
+ ? "it is not imported, and no module of its package names it"
263
+ : `no name from \`${found.through}\`, as the project imports it, reaches its declaration`;
264
+ }
265
+ /** Why a key found for a call is not given: read back, it names another declaration. */
266
+ export const UNRESOLVED_REASON = "the key that names it resolves to another declaration";
267
+ /** The version of each package a file's project runs, read once per file. */
268
+ const versionsRead = new WeakMap();
269
+ function versionFor(file, packageName) {
270
+ let known = versionsRead.get(file);
271
+ if (known === undefined) {
272
+ known = new Map();
273
+ versionsRead.set(file, known);
274
+ }
275
+ if (!known.has(packageName)) {
276
+ const read = packageVersionOf({ file: file.fileName }, packageName);
277
+ known.set(packageName, read.kind === "exact" ? read.version : undefined);
278
+ }
279
+ return known.get(packageName);
280
+ }
281
+ /** The code a reference is written as, on one line: `Words.parse`. */
282
+ function writtenText(reference) {
283
+ return codeOnOneLine(reference.getText());
284
+ }
285
+ /**
286
+ * The `facts` key for `declared`, a function, property or class outside the project, as
287
+ * `reference` (the callee of a call, a class named in a decorator) reaches it: the module the
288
+ * project imports it from, as written, followed out of the project's own re-exports; for a global,
289
+ * a module that exports it (`TypeQueries.factModuleOf`). The name is the one that resolves to it
290
+ * in that module (`TypeQueries.factNameOf`), and the version the one `"@versions"` is checked
291
+ * against: the installed version of the package that owns the module, left out for the
292
+ * platform's modules and when it is not known. `unnamed` when no module names it. Every hint,
293
+ * `Finding.needs`, quick fix and `coverage --facts` takes its key from here.
294
+ *
295
+ * Each key is read back with `TypeQueries.factTarget` before it is given: one that does not resolve
296
+ * to `declared` would be a line that does nothing, so the call is `unnamed` instead.
297
+ */
298
+ export function factKeyOf(types, declared, reference) {
299
+ const found = types.factModuleOf(declared.node, reference);
300
+ if (found.kind === "unnamed") {
301
+ return { kind: "unnamed", name: writtenText(reference), reason: unnamedReason(found) };
302
+ }
303
+ const back = types.factTarget(found.module, found.name);
304
+ if (back.kind !== "found" || !back.declarations.has(declared.node)) {
305
+ return { kind: "unnamed", name: writtenText(reference), reason: UNRESOLVED_REASON };
306
+ }
307
+ const version = found.platform
308
+ ? undefined
309
+ : versionFor(reference.getSourceFile(), packageOfModule(found.module));
310
+ return {
311
+ kind: "named",
312
+ module: found.module,
313
+ name: found.name,
314
+ ...(version === undefined ? {} : { version }),
315
+ };
316
+ }
317
+ function skippedParentheses(node) {
318
+ let at = node;
319
+ while (ts.isParenthesizedExpression(at.parent))
320
+ at = at.parent;
321
+ return at;
322
+ }
323
+ /**
324
+ * What a `facts` line states of the function `reference` calls: `rejects` when the call's value is
325
+ * a promise (a thenable, by its type), `throws` otherwise and for a constructor (`new X()`). A
326
+ * function referenced without a call is read by what its declaration returns.
327
+ */
328
+ export function factSideOf(types, declared, reference) {
329
+ const outer = skippedParentheses(reference);
330
+ const parent = outer.parent;
331
+ if (ts.isNewExpression(parent) && parent.expression === outer)
332
+ return "throws";
333
+ if (ts.isCallExpression(parent) && parent.expression === outer) {
334
+ return types.isPromiseLike(parent) ? "rejects" : "throws";
335
+ }
336
+ const node = declared.node;
337
+ return ts.isFunctionLike(node) && types.returnsPromiseLike(node) ? "rejects" : "throws";
338
+ }
339
+ /**
340
+ * The `facts` line a call that no line states needs (`Finding.needs`): its key (`factKeyOf`) and
341
+ * the side the function called states (`factSideOf`); `unnamed` when no key can name it.
342
+ */
343
+ export function factNeedOf(types, declared, reference) {
344
+ const key = factKeyOf(types, declared, reference);
345
+ if (key.kind === "unnamed") {
346
+ return { kind: "unnamed", unnamed: { name: key.name, reason: key.reason } };
347
+ }
348
+ const { module, name, version } = key;
349
+ return {
350
+ kind: "named",
351
+ need: {
352
+ module,
353
+ name,
354
+ ...(version === undefined ? {} : { version }),
355
+ states: [factSideOf(types, declared, reference)],
356
+ },
357
+ };
358
+ }
359
+ /** A key as the config writes it: as an identifier where it is one, else quoted. */
360
+ export function factKeyText(key) {
361
+ return /^[A-Za-z_$][\w$]*$/.test(key) ? key : JSON.stringify(key);
362
+ }
363
+ /**
364
+ * The config's `facts` line for a key, with `value` as the line's value (`{ throws: [] }`), as
365
+ * a hint shows it: `facts: { "kit": { "@versions": "2.4.0", load: { throws: [] } } }`.
366
+ */
367
+ export function factLineText(key, value) {
368
+ const version = key.version === undefined
369
+ ? ""
370
+ : `${JSON.stringify("@versions")}: ${JSON.stringify(key.version)}, `;
371
+ return `facts: { ${JSON.stringify(key.module)}: { ${version}${factKeyText(key.name)}: ${value} } }`;
117
372
  }
118
373
  /** How many `const` names are followed back to the promise they hold. */
119
374
  const MAX_ALIASES = 4;
@@ -140,7 +395,11 @@ export function packageFunctionOf(name, ctx) {
140
395
  if (declared === undefined)
141
396
  return undefined;
142
397
  if (!types.isOwnFile(declared.file)) {
143
- return { declared, through: ts.isPropertyAccessExpression(node) ? node.expression : node };
398
+ const receiver = ts.isPropertyAccessExpression(node) ? node.expression : undefined;
399
+ return {
400
+ declared: receiver === undefined ? declared : { ...declared, receiver },
401
+ through: receiver ?? node,
402
+ };
144
403
  }
145
404
  const local = declared.node;
146
405
  if (ts.isBindingElement(local)) {
@@ -159,6 +418,27 @@ export function packageFunctionOf(name, ctx) {
159
418
  }
160
419
  return undefined;
161
420
  }
421
+ /**
422
+ * The facts line for what a call calls (`useEffect(…)`, `db.watch(…)`): the package function
423
+ * itself, or the one a name of the project stands for (`const watch = db.watch`). The config's
424
+ * line first, then the ones the packs ship; undefined for the project's own functions and for one
425
+ * no line names.
426
+ */
427
+ export function callFactOf(call, ctx, wanted) {
428
+ const { types } = ctx;
429
+ const name = calleeName(call);
430
+ const symbol = name === undefined ? undefined : types.symbolAt(name);
431
+ const declared = symbol === undefined ? undefined : types.declarationOf(symbol);
432
+ if (declared === undefined)
433
+ return undefined;
434
+ if (types.isOwnFile(declared.file)) {
435
+ const aliased = ts.isIdentifier(call.expression)
436
+ ? packageFunctionOf(call.expression, ctx)
437
+ : undefined;
438
+ return aliased === undefined ? undefined : packageFactOf(aliased.declared, ctx, wanted);
439
+ }
440
+ return packageFactOf(name === undefined ? declared : withReceiverOf(declared, name), ctx, wanted);
441
+ }
162
442
  /**
163
443
  * The package declaration an awaited expression comes from: the function of a call, the property
164
444
  * read (`api.cacheEntryRemoved`), or, for a name, the property it was destructured from
@@ -180,18 +460,14 @@ function promiseSource(expression, ctx, depth) {
180
460
  const declared = symbol === undefined ? undefined : types.declarationOf(symbol);
181
461
  if (declared === undefined)
182
462
  return undefined;
183
- const through = ts.isCallExpression(node)
184
- ? node.expression
185
- : ts.isPropertyAccessExpression(node)
186
- ? node.expression
187
- : node;
188
- if (!ts.isIdentifier(node) || !types.isOwnFile(declared.file))
189
- return { declared, through };
463
+ if (!ts.isIdentifier(node) || !types.isOwnFile(declared.file)) {
464
+ return withReceiverOf(declared, name);
465
+ }
190
466
  const local = declared.node;
191
467
  if (ts.isBindingElement(local)) {
192
468
  const property = types.bindingPropertyOf(local);
193
469
  const source = property === undefined ? undefined : types.declarationOf(property);
194
- return source === undefined ? undefined : { declared: source, through: undefined };
470
+ return source;
195
471
  }
196
472
  if (ts.isVariableDeclaration(local) &&
197
473
  (ts.getCombinedNodeFlags(local) & ts.NodeFlags.Const) !== 0 &&
@@ -207,7 +483,213 @@ function promiseSource(expression, ctx, depth) {
207
483
  */
208
484
  export function neverRejectsFactOf(expression, ctx) {
209
485
  const source = promiseSource(expression, ctx, 0);
210
- const found = source === undefined ? undefined : packageFactOf(source.declared, source.through, ctx);
486
+ const found = source === undefined ? undefined : packageFactOf(source, ctx, "neverRejects");
487
+ if (found?.kind === "unread")
488
+ return found;
211
489
  return found?.fact.neverRejects === true ? found : undefined;
212
490
  }
491
+ /**
492
+ * The facts line that says a value comes from outside the program (`external: true`), when one
493
+ * does: the result of a call of the package function (`redis.get(key)`), or a read of the
494
+ * package property (`response.data`). Undefined otherwise.
495
+ */
496
+ export function externalFactOf(expression, ctx) {
497
+ const node = unwrapped(expression);
498
+ let found;
499
+ if (ts.isCallExpression(node)) {
500
+ found = callFactOf(node, ctx, "external");
501
+ }
502
+ else if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name)) {
503
+ const symbol = ctx.types.symbolAt(node.name);
504
+ const declared = symbol === undefined ? undefined : ctx.types.declarationOf(symbol);
505
+ found =
506
+ declared === undefined
507
+ ? undefined
508
+ : packageFactOf({ ...declared, receiver: node.expression }, ctx, "external");
509
+ }
510
+ if (found?.kind === "unread")
511
+ return found;
512
+ return found?.fact.external === true ? found : undefined;
513
+ }
514
+ /** The edit distance between two texts, for the closest declared path. */
515
+ function distance(a, b) {
516
+ let row = Array.from({ length: b.length + 1 }, (_, index) => index);
517
+ for (let i = 1; i <= a.length; i++) {
518
+ const next = [i];
519
+ for (let j = 1; j <= b.length; j++) {
520
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
521
+ next.push(Math.min((row[j] ?? 0) + 1, (next[j - 1] ?? 0) + 1, (row[j - 1] ?? 0) + cost));
522
+ }
523
+ row = next;
524
+ }
525
+ return row[b.length] ?? 0;
526
+ }
527
+ /**
528
+ * The name closest to `name` of those a module has (`TypeQueries.factNames`): one that ends in the
529
+ * same name first, else the nearest by spelling; undefined when none is near.
530
+ */
531
+ function closestPath(name, paths) {
532
+ const last = name.split(".").at(-1) ?? name;
533
+ const same = paths.filter((one) => one === last || one.endsWith(`.${last}`));
534
+ const pool = same.length > 0 ? same : paths;
535
+ const limit = same.length > 0 ? Infinity : Math.max(2, Math.floor(name.length / 3));
536
+ let best;
537
+ for (const one of pool) {
538
+ const cost = distance(name, one);
539
+ if (cost <= limit && (best === undefined || cost < best.cost))
540
+ best = { path: one, cost };
541
+ }
542
+ return best?.path;
543
+ }
544
+ /** The key closest to `name` that the module has, in the grain `name` is written in. */
545
+ function nearKey(name, paths) {
546
+ const grain = factGrainOf(name);
547
+ if (grain.kind !== "class")
548
+ return closestPath(name, paths);
549
+ const near = closestPath(grain.owner, paths);
550
+ return near === undefined ? undefined : `${near}.${WILDCARD}`;
551
+ }
552
+ /**
553
+ * The kinds of a `facts` line that can apply to a declaration: `throws` for any function, method
554
+ * or class (a function can throw before it returns, whatever its type says), and `rejects` too
555
+ * unless every return its declaration states cannot be a promise (`mayReturnPromise`: a type
556
+ * parameter, `any` or `unknown` can be one). Empty for anything else, whose kind the declaration
557
+ * does not say. The kinds a hint, a quick fix or `coverage --facts` suggest for a call
558
+ * (`factSideOf`) are always among them, so no line stateward suggests is warned of.
559
+ */
560
+ export function factSidesOfDeclaration(types, node) {
561
+ if (ts.isClassDeclaration(node))
562
+ return ["throws"];
563
+ if (!ts.isFunctionLike(node))
564
+ return [];
565
+ return types.mayReturnPromise(node) ? ["throws", "rejects"] : ["throws"];
566
+ }
567
+ /** Each key of the config's `facts` resolved in one program, in the order the config lists them. */
568
+ export function checkFactKeys(facts, types) {
569
+ const checks = [];
570
+ for (const [module, functions] of Object.entries(facts)) {
571
+ for (const name of Object.keys(functions)) {
572
+ const target = types.factTarget(module, name);
573
+ const { kind } = target;
574
+ if (target.kind === "found") {
575
+ const sides = [...target.declarations, ...target.throughReceiver.keys()].flatMap((node) => factSidesOfDeclaration(types, node));
576
+ checks.push({ module, name, kind, fits: neededSides(sides) });
577
+ continue;
578
+ }
579
+ const near = kind === "no-name" ? nearKey(name, types.factNames(module)) : undefined;
580
+ checks.push({ module, name, kind, ...(near === undefined ? {} : { near }) });
581
+ }
582
+ }
583
+ return checks;
584
+ }
585
+ /** A digest of the keys of `facts`: what `checkFactKeys` depends on. */
586
+ export function factKeysDigest(facts) {
587
+ const keys = Object.entries(facts).map(([module, functions]) => [module, Object.keys(functions)]);
588
+ return createHash("sha1").update(JSON.stringify(keys)).digest("hex");
589
+ }
590
+ const KINDS = ["found", "no-module", "no-name"];
591
+ /** `checkFactKeys`'s result as `JSON.stringify` wrote it; undefined for anything else. */
592
+ export function readFactKeyChecks(text) {
593
+ let value;
594
+ try {
595
+ value = JSON.parse(text);
596
+ }
597
+ catch {
598
+ return undefined;
599
+ }
600
+ if (!Array.isArray(value))
601
+ return undefined;
602
+ const items = value;
603
+ const checks = [];
604
+ for (const item of items) {
605
+ if (typeof item !== "object" || item === null)
606
+ return undefined;
607
+ const module = Reflect.get(item, "module");
608
+ const name = Reflect.get(item, "name");
609
+ const kind = KINDS.find((one) => one === Reflect.get(item, "kind"));
610
+ const near = Reflect.get(item, "near");
611
+ const fits = Reflect.get(item, "fits");
612
+ if (typeof module !== "string" || typeof name !== "string" || kind === undefined) {
613
+ return undefined;
614
+ }
615
+ if (near !== undefined && typeof near !== "string")
616
+ return undefined;
617
+ // A key found carries the kinds that fit it; a check written before they were kept is read again.
618
+ const sides = Array.isArray(fits)
619
+ ? FACT_SIDES.filter((side) => fits.includes(side))
620
+ : undefined;
621
+ if ((kind === "found") !== (sides !== undefined))
622
+ return undefined;
623
+ if (sides !== undefined && Array.isArray(fits) && sides.length !== fits.length)
624
+ return undefined;
625
+ checks.push({
626
+ module,
627
+ name,
628
+ kind,
629
+ ...(near === undefined ? {} : { near }),
630
+ ...(sides === undefined ? {} : { fits: sides }),
631
+ });
632
+ }
633
+ return checks;
634
+ }
635
+ /** `throws`, `rejects`, or both, as a warning names the kinds of a line. */
636
+ function kindsText(sides) {
637
+ return sides.map((side) => `\`${side}\``).join(" and ");
638
+ }
639
+ /**
640
+ * The warning for a line whose kinds can apply to none of the functions its key names, in any
641
+ * project (`FactKeyCheck.fits`): kinds are strict, so such a line settles nothing. Only a
642
+ * `rejects` line can be one, when every declared signature returns a type that cannot be a
643
+ * promise; `throws` always fits a function. Undefined when one of its kinds fits, or the key names
644
+ * no function.
645
+ */
646
+ function kindMisfit(checks, facts) {
647
+ const [first] = checks;
648
+ if (first === undefined)
649
+ return undefined;
650
+ const line = facts[first.module]?.[first.name];
651
+ const stated = FACT_SIDES.filter((side) => line?.[side] !== undefined);
652
+ const fits = neededSides(checks.flatMap((one) => one.fits ?? []));
653
+ if (stated.length === 0 || fits.length === 0 || stated.some((side) => fits.includes(side))) {
654
+ return undefined;
655
+ }
656
+ return `\`${first.module}\`'s \`${first.name}\` returns no promise, so the line's ${kindsText(stated)} settles nothing: state what it throws in \`throws\``;
657
+ }
658
+ /**
659
+ * Each line of the config's `facts`, as the projects resolve it (`checkFactKeys`, one list per
660
+ * project): a line one project resolves is matched; else a warning for a name its module does
661
+ * not have, with the closest name it has ("`ioredis` has no function `Redis.hget`; did you mean
662
+ * `RedisCommander.hget`?"), and "not checked" for a module no project's types load.
663
+ */
664
+ export function unmatchedFacts(projects, facts = {}) {
665
+ const byKey = new Map();
666
+ for (const checks of projects) {
667
+ for (const check of checks) {
668
+ const key = `${check.module}\u0000${check.name}`;
669
+ byKey.set(key, [...(byKey.get(key) ?? []), check]);
670
+ }
671
+ }
672
+ const unmatched = [];
673
+ const notChecked = [];
674
+ for (const checks of byKey.values()) {
675
+ if (checks.some((one) => one.kind === "found")) {
676
+ const misfit = kindMisfit(checks, facts);
677
+ if (misfit !== undefined)
678
+ unmatched.push(misfit);
679
+ continue;
680
+ }
681
+ const missing = checks.find((one) => one.kind === "no-name");
682
+ const [first] = checks;
683
+ if (missing !== undefined) {
684
+ const why = missing.near === undefined ? "" : `; did you mean \`${missing.near}\`?`;
685
+ const grain = factGrainOf(missing.name);
686
+ const what = grain.kind === "class" ? `class \`${grain.owner}\`` : `function \`${missing.name}\``;
687
+ unmatched.push(`\`${missing.module}\` has no ${what}${why}`);
688
+ }
689
+ else if (first !== undefined) {
690
+ notChecked.push(`not checked: whether \`${first.module}\` declares \`${first.name}\`: the project's types do not load \`${first.module}\``);
691
+ }
692
+ }
693
+ return { unmatched, notChecked };
694
+ }
213
695
  //# sourceMappingURL=package-facts.js.map
package/dist/plan.d.ts CHANGED
@@ -27,7 +27,7 @@ export type Plan = {
27
27
  rules: readonly PlanRow[];
28
28
  };
29
29
  /**
30
- * The suggested order: core rules, then coverage, then add-ons; within a tier the fewest findings
30
+ * The suggested order: core rules, then coverage, then convention rules, then add-ons; within a tier the fewest findings
31
31
  * first (a rule with nothing to fix costs nothing to turn on, and a big one never comes first:
32
32
  * beta feedback), then the most quick fixes, then the pack order of
33
33
  * the config, then the rule id. `result` must come from a run of the `all` selection. Rules the
package/dist/plan.js CHANGED
@@ -1,5 +1,10 @@
1
1
  import { ruleIsOn } from "./severity.js";
2
- const TIER_RANK = { core: 0, coverage: 1, addon: 2 };
2
+ const TIER_RANK = {
3
+ core: 0,
4
+ coverage: 1,
5
+ convention: 2,
6
+ addon: 3,
7
+ };
3
8
  function compareText(a, b) {
4
9
  if (a < b)
5
10
  return -1;
@@ -13,7 +18,7 @@ function compareCandidates(a, b) {
13
18
  compareText(a.ruleId, b.ruleId));
14
19
  }
15
20
  /**
16
- * The suggested order: core rules, then coverage, then add-ons; within a tier the fewest findings
21
+ * The suggested order: core rules, then coverage, then convention rules, then add-ons; within a tier the fewest findings
17
22
  * first (a rule with nothing to fix costs nothing to turn on, and a big one never comes first:
18
23
  * beta feedback), then the most quick fixes, then the pack order of
19
24
  * the config, then the rule id. `result` must come from a run of the `all` selection. Rules the