@stateward/core 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 (75) hide show
  1. package/dist/analyses.d.ts +37 -0
  2. package/dist/analyses.js +57 -0
  3. package/dist/backend/fingerprints.d.ts +3 -1
  4. package/dist/backend/fingerprints.js +198 -9
  5. package/dist/backend/program-record.d.ts +7 -0
  6. package/dist/backend/program-size.d.ts +32 -0
  7. package/dist/backend/program-size.js +166 -0
  8. package/dist/backend/typescript6.d.ts +62 -32
  9. package/dist/backend/typescript6.js +1615 -164
  10. package/dist/baseline.d.ts +1 -1
  11. package/dist/baseline.js +14 -10
  12. package/dist/cache.d.ts +92 -4
  13. package/dist/cache.js +257 -68
  14. package/dist/checker.d.ts +28 -3
  15. package/dist/checker.js +42 -8
  16. package/dist/class-id.d.ts +34 -0
  17. package/dist/class-id.js +93 -0
  18. package/dist/code-text.d.ts +8 -0
  19. package/dist/code-text.js +66 -0
  20. package/dist/config-file.js +7 -5
  21. package/dist/config.d.ts +10 -2
  22. package/dist/config.js +490 -48
  23. package/dist/define.d.ts +8 -2
  24. package/dist/disk-cache.d.ts +34 -2
  25. package/dist/disk-cache.js +82 -15
  26. package/dist/engine.d.ts +64 -3
  27. package/dist/engine.js +474 -59
  28. package/dist/fact-lines.d.ts +31 -0
  29. package/dist/fact-lines.js +197 -0
  30. package/dist/facts-versions.d.ts +27 -0
  31. package/dist/facts-versions.js +99 -0
  32. package/dist/fixes.js +4 -1
  33. package/dist/ignores.d.ts +11 -0
  34. package/dist/ignores.js +74 -27
  35. package/dist/implementation.d.ts +0 -6
  36. package/dist/implementation.js +0 -17
  37. package/dist/index.d.ts +9 -9
  38. package/dist/index.js +12 -7
  39. package/dist/internal.d.ts +13 -6
  40. package/dist/internal.js +7 -3
  41. package/dist/journal.d.ts +40 -0
  42. package/dist/journal.js +197 -0
  43. package/dist/lazy.d.ts +8 -1
  44. package/dist/lazy.js +27 -2
  45. package/dist/ledger.d.ts +2 -2
  46. package/dist/ledger.js +2 -2
  47. package/dist/memory-plan.d.ts +121 -0
  48. package/dist/memory-plan.js +174 -0
  49. package/dist/off-by-default.d.ts +13 -0
  50. package/dist/off-by-default.js +15 -0
  51. package/dist/options.d.ts +21 -5
  52. package/dist/options.js +22 -7
  53. package/dist/package-facts.d.ts +211 -17
  54. package/dist/package-facts.js +520 -38
  55. package/dist/plan.d.ts +1 -1
  56. package/dist/plan.js +7 -2
  57. package/dist/release.d.ts +12 -21
  58. package/dist/release.js +26 -38
  59. package/dist/renamed.d.ts +22 -3
  60. package/dist/renamed.js +50 -16
  61. package/dist/rollout.js +7 -4
  62. package/dist/severity.d.ts +1 -1
  63. package/dist/severity.js +17 -3
  64. package/dist/test-runner.d.ts +18 -0
  65. package/dist/test-runner.js +483 -0
  66. package/dist/testing.d.ts +3 -3
  67. package/dist/testing.js +5 -5
  68. package/dist/timing.d.ts +17 -7
  69. package/dist/timing.js +60 -38
  70. package/dist/types.d.ts +704 -20
  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
package/dist/cache.js CHANGED
@@ -7,8 +7,11 @@ import { isQueryKind } from "./backend/program-record.js";
7
7
  * its rule key (`ruleKey`): the findings the rule reported on that file, and a project rule's
8
8
  * summary; with the hash of each declaration (or whole file) of another file the rules read there. A
9
9
  * file whose fingerprint and reads are unchanged is not looked at again.
10
- * - per project rule, under its rule key: a hash of all its summaries, and the findings its check
11
- * produced from them. Equal summaries give equal findings (a project rule decides from its
10
+ * - per analysis a rule reads (`Plugin.analyses`), under its key (`analysisKey`): a hash of its
11
+ * summaries, and the fingerprint of what it solved from them; a project rule that reads it has
12
+ * that fingerprint in its inputs, so it is checked again only when the analysis changes.
13
+ * - per project rule, under its rule key: a hash of all its summaries (and of the analyses it
14
+ * reads), and the findings its check produced from them. Equal summaries give equal findings (a project rule decides from its
12
15
  * summaries and options alone), so an edit that leaves every summary as it was does not run
13
16
  * the check again (early cut-off).
14
17
  *
@@ -16,9 +19,9 @@ import { isQueryKind } from "./backend/program-record.js";
16
19
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
17
20
  */
18
21
  /** Bumped whenever what is stored, or how a key is computed, changes. */
19
- export const CACHE_FORMAT = 10;
22
+ export const CACHE_FORMAT = 18;
20
23
  /** Frozen all the way down: a cached summary is shared between runs, so no rule may change it. */
21
- function deepFreeze(value) {
24
+ export function deepFreeze(value) {
22
25
  if (typeof value === "object" && value !== null) {
23
26
  for (const member of Object.values(value))
24
27
  deepFreeze(member);
@@ -38,6 +41,8 @@ export function summaryOf(value) {
38
41
  export function summaryFromText(text, hash) {
39
42
  return { hash, form: { kind: "text", text } };
40
43
  }
44
+ /** The hash of each summary value handed out (`summaryValue`), by the value. */
45
+ const hashes = new WeakMap();
41
46
  /** The summary's value, parsed from its text once and frozen; the text is then let go. */
42
47
  export function summaryValue(summary) {
43
48
  const { form } = summary;
@@ -45,9 +50,19 @@ export function summaryValue(summary) {
45
50
  return form.value;
46
51
  const parsed = JSON.parse(form.text);
47
52
  const value = deepFreeze(isJson(parsed) ? parsed : null);
53
+ if (typeof value === "object" && value !== null)
54
+ hashes.set(value, summary.hash);
48
55
  summary.form = { kind: "parsed", value };
49
56
  return value;
50
57
  }
58
+ /**
59
+ * The hash of the JSON text of a summary the engine handed to a project rule's `check`, an
60
+ * analysis's `solve` or an editor contribution: equal hashes are equal summaries. Undefined for a
61
+ * value the engine did not hand out (one a test built), and for `null` or a primitive.
62
+ */
63
+ export function summaryHash(value) {
64
+ return typeof value === "object" && value !== null ? hashes.get(value) : undefined;
65
+ }
51
66
  /**
52
67
  * The summary's JSON text: kept, or written again from the parsed value. JSON text parsed and
53
68
  * written again is the same text (`JSON.stringify` wrote it), so the hash still matches it.
@@ -56,13 +71,49 @@ export function summaryText(summary) {
56
71
  const { form } = summary;
57
72
  return form.kind === "text" ? form.text : JSON.stringify(form.value);
58
73
  }
74
+ /** Entries no run among the last this many used are dropped when the cache is saved. */
75
+ export const KEEP_RUNS = 3;
76
+ /** Notes that this run uses the entries under `key`, so a save keeps them. */
77
+ export function useKey(cache, key) {
78
+ if (cache.used.get(key) !== cache.run)
79
+ cache.used.set(key, cache.run);
80
+ }
81
+ /**
82
+ * Drops the entries under keys that none of the last `runs` runs used (`KEEP_RUNS` by default):
83
+ * the results of a rule or an analysis under an earlier config or code, and verdicts of fixes no
84
+ * longer shown. Without it, a cache kept every key it ever held and grew past what can be written.
85
+ * `runs = 1` keeps only what this run used. Returns whether anything was dropped.
86
+ */
87
+ export function pruneUnused(cache, runs = KEEP_RUNS) {
88
+ const oldest = cache.run - runs + 1;
89
+ const stale = new Set([...cache.used].filter(([, last]) => last < oldest).map(([key]) => key));
90
+ if (stale.size === 0)
91
+ return false;
92
+ for (const key of stale)
93
+ cache.used.delete(key);
94
+ // A key no run stamps (a file's own entries, such as its ignore comments) is kept with its file.
95
+ for (const entry of cache.files.values()) {
96
+ const rules = [...entry.rules].filter(([key]) => !stale.has(key));
97
+ if (rules.length !== entry.rules.size)
98
+ entry.rules = new Map(rules);
99
+ }
100
+ for (const map of [cache.projects, cache.analyses, cache.verdicts]) {
101
+ for (const key of [...map.keys()])
102
+ if (stale.has(key))
103
+ map.delete(key);
104
+ }
105
+ return true;
106
+ }
59
107
  export function emptyCache() {
60
108
  return {
61
109
  files: new Map(),
62
110
  projects: new Map(),
111
+ analyses: new Map(),
63
112
  programs: new Map(),
64
113
  verdicts: new Map(),
65
114
  changed: false,
115
+ run: 1,
116
+ used: new Map(),
66
117
  };
67
118
  }
68
119
  export function sha1(text) {
@@ -92,43 +143,91 @@ export function ruleKey(input) {
92
143
  code,
93
144
  ]));
94
145
  }
95
- export function toSnapshot(cache) {
96
- const files = {};
97
- for (const [file, entry] of [...cache.files].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
98
- const rules = {};
99
- for (const [key, result] of entry.rules) {
100
- rules[key] = {
101
- findings: result.findings,
102
- ...(result.summary === undefined
103
- ? {}
104
- : { summary: summaryText(result.summary), hash: result.summary.hash }),
105
- ...(result.marks === undefined ? {} : { marks: result.marks }),
106
- };
107
- }
108
- files[file] = {
109
- fingerprint: entry.fingerprint,
110
- rules,
111
- reads: Object.fromEntries([...entry.reads].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
146
+ /**
147
+ * What an analysis's results depend on besides the files: its id, its code, the facts about
148
+ * packages its `summarize` reads, and the cache format.
149
+ */
150
+ export function analysisKey(input) {
151
+ return sha1(JSON.stringify([
152
+ CACHE_FORMAT,
153
+ "analysis",
154
+ input.id,
155
+ input.facts,
156
+ [input.analysis.summarize.toString(), input.analysis.solve.toString()],
157
+ ]));
158
+ }
159
+ function byKey(entries) {
160
+ return [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
161
+ }
162
+ /** One file's results as plain JSON (`CacheSnapshot.files`); read back with `parseFileEntry`. */
163
+ export function fileSnapshot(entry) {
164
+ const rules = {};
165
+ for (const [key, result] of entry.rules) {
166
+ rules[key] = {
167
+ findings: result.findings,
168
+ ...(result.summary === undefined
169
+ ? {}
170
+ : { summary: summaryText(result.summary), hash: result.summary.hash }),
171
+ ...(result.marks === undefined ? {} : { marks: result.marks }),
112
172
  };
113
173
  }
114
- const projects = {};
115
- for (const [key, entry] of cache.projects) {
116
- projects[key] = {
117
- inputs: entry.inputs,
118
- findings: entry.findings,
119
- ...(entry.marks === undefined ? {} : { marks: entry.marks }),
120
- };
174
+ return { fingerprint: entry.fingerprint, rules, reads: Object.fromEntries(byKey(entry.reads)) };
175
+ }
176
+ function projectSnapshot(entry) {
177
+ return {
178
+ inputs: entry.inputs,
179
+ findings: entry.findings,
180
+ ...(entry.unstated === undefined ? {} : { unstated: entry.unstated }),
181
+ ...(entry.marks === undefined ? {} : { marks: entry.marks }),
182
+ };
183
+ }
184
+ /** Everything but the files and the projects, which can be large and are written one by one. */
185
+ function smallParts(cache) {
186
+ const analyses = {};
187
+ for (const [key, entry] of cache.analyses) {
188
+ analyses[key] = { inputs: entry.inputs, fingerprint: entry.fingerprint };
121
189
  }
122
190
  return {
123
191
  format: CACHE_FORMAT,
124
- files,
125
- projects,
192
+ run: cache.run,
193
+ used: Object.fromEntries(byKey(cache.used)),
194
+ analyses,
126
195
  programs: Object.fromEntries([...cache.programs]),
127
- verdicts: Object.fromEntries([...cache.verdicts]
128
- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
129
- .map(([key, verdict]) => [key, verdict.kind === "compiles" ? null : verdict.error])),
196
+ verdicts: Object.fromEntries(byKey(cache.verdicts).map(([key, verdict]) => [
197
+ key,
198
+ verdict.kind === "compiles" ? null : verdict.error,
199
+ ])),
130
200
  };
131
201
  }
202
+ export function toSnapshot(cache) {
203
+ const files = {};
204
+ for (const [file, entry] of byKey(cache.files))
205
+ files[file] = fileSnapshot(entry);
206
+ const projects = {};
207
+ for (const [key, entry] of cache.projects)
208
+ projects[key] = projectSnapshot(entry);
209
+ return { ...smallParts(cache), files, projects };
210
+ }
211
+ /**
212
+ * The snapshot's JSON text in pieces, for a writer that never holds the whole text (a large
213
+ * project's is more than one string can hold): `toSnapshot`'s value, one file's results per piece.
214
+ */
215
+ export function* snapshotChunks(cache) {
216
+ const small = JSON.stringify(smallParts(cache));
217
+ yield `${small.slice(0, -1)},"projects":{`;
218
+ let first = true;
219
+ for (const [key, entry] of byKey(cache.projects)) {
220
+ yield `${first ? "" : ","}${JSON.stringify(key)}:${JSON.stringify(projectSnapshot(entry))}`;
221
+ first = false;
222
+ }
223
+ yield '},"files":{';
224
+ first = true;
225
+ for (const [file, entry] of byKey(cache.files)) {
226
+ yield `${first ? "" : ","}${JSON.stringify(file)}:${JSON.stringify(fileSnapshot(entry))}`;
227
+ first = false;
228
+ }
229
+ yield "}}";
230
+ }
132
231
  function isFields(value) {
133
232
  return typeof value === "object" && value !== null && !Array.isArray(value);
134
233
  }
@@ -221,9 +320,18 @@ function parseProgramRecord(value) {
221
320
  fingerprints[file] = fingerprint;
222
321
  }
223
322
  const reads = stringRecord(value.reads);
224
- if (queries === undefined || files === undefined || reads === undefined)
323
+ const imports = parseList(value.imports, (name) => (typeof name === "string" ? name : undefined));
324
+ if (queries === undefined ||
325
+ files === undefined ||
326
+ reads === undefined ||
327
+ imports === undefined) {
328
+ return undefined;
329
+ }
330
+ // A record of a build before facts were resolved through the program has none: they are asked again.
331
+ const facts = value.facts === undefined ? {} : stringRecord(value.facts);
332
+ if (facts === undefined)
225
333
  return undefined;
226
- return { inputs: value.inputs, queries, files, fingerprints, reads };
334
+ return { inputs: value.inputs, queries, files, fingerprints, reads, imports, facts };
227
335
  }
228
336
  /** A JSON object of strings, as a record; undefined when anything else. */
229
337
  function stringRecord(value) {
@@ -276,6 +384,49 @@ function parseStrings(value) {
276
384
  }
277
385
  return found;
278
386
  }
387
+ const SIDES = ["throws", "rejects"];
388
+ /** A `facts` line a finding needs (`FactNeed`); undefined when it has another shape. */
389
+ function parseNeed(value) {
390
+ if (!isFields(value))
391
+ return undefined;
392
+ const { module, name, version } = value;
393
+ const states = parseStrings(value.states);
394
+ if (typeof module !== "string" || typeof name !== "string" || states === undefined) {
395
+ return undefined;
396
+ }
397
+ if (version !== undefined && typeof version !== "string")
398
+ return undefined;
399
+ const sides = SIDES.filter((side) => states.includes(side));
400
+ if (sides.length !== states.length)
401
+ return undefined;
402
+ return { module, name, ...(version === undefined ? {} : { version }), states: sides };
403
+ }
404
+ /** A call no `facts` key can name (`UnnamedFact`); undefined when it has another shape. */
405
+ function parseUnnamed(value) {
406
+ if (!isFields(value))
407
+ return undefined;
408
+ const { name, reason } = value;
409
+ return typeof name === "string" && typeof reason === "string" ? { name, reason } : undefined;
410
+ }
411
+ /** A place judged leaving out unstated package calls (`UnstatedPlace`); undefined for another shape. */
412
+ function parseUnstated(value) {
413
+ if (!isFields(value) || typeof value.ruleId !== "string")
414
+ return undefined;
415
+ const location = parseLocation(value.location);
416
+ const needs = value.needs === undefined ? undefined : parseList(value.needs, parseNeed);
417
+ const unnamed = value.unnamed === undefined ? undefined : parseList(value.unnamed, parseUnnamed);
418
+ if (location === undefined ||
419
+ (value.needs !== undefined && needs === undefined) ||
420
+ (value.unnamed !== undefined && unnamed === undefined)) {
421
+ return undefined;
422
+ }
423
+ return {
424
+ ruleId: value.ruleId,
425
+ location,
426
+ ...(needs === undefined ? {} : { needs }),
427
+ ...(unnamed === undefined ? {} : { unnamed }),
428
+ };
429
+ }
279
430
  export function parseFinding(value) {
280
431
  if (!isFields(value))
281
432
  return undefined;
@@ -293,6 +444,12 @@ export function parseFinding(value) {
293
444
  if (value.guarantees !== undefined && guarantees === undefined)
294
445
  return undefined;
295
446
  if (kind === "unknown") {
447
+ const needs = value.needs === undefined ? undefined : parseList(value.needs, parseNeed);
448
+ if (value.needs !== undefined && needs === undefined)
449
+ return undefined;
450
+ const unnamed = value.unnamed === undefined ? undefined : parseList(value.unnamed, parseUnnamed);
451
+ if (value.unnamed !== undefined && unnamed === undefined)
452
+ return undefined;
296
453
  return {
297
454
  kind,
298
455
  ruleId,
@@ -301,6 +458,8 @@ export function parseFinding(value) {
301
458
  location,
302
459
  ...(value.listed === true ? { listed: true } : {}),
303
460
  ...(guarantees === undefined ? {} : { guarantees }),
461
+ ...(needs === undefined ? {} : { needs }),
462
+ ...(unnamed === undefined ? {} : { unnamed }),
304
463
  };
305
464
  }
306
465
  if (kind !== "problem" || !isSeverity(value.severity))
@@ -330,6 +489,37 @@ export function parseFinding(value) {
330
489
  ...(guarantees === undefined ? {} : { guarantees }),
331
490
  };
332
491
  }
492
+ /** One file's results as `fileSnapshot` wrote them; undefined when anything has another shape. */
493
+ export function parseFileEntry(entry) {
494
+ if (!isFields(entry) || typeof entry.fingerprint !== "string" || !isFields(entry.rules)) {
495
+ return undefined;
496
+ }
497
+ const reads = stringRecord(entry.reads);
498
+ if (reads === undefined)
499
+ return undefined;
500
+ const rules = new Map();
501
+ for (const [key, result] of Object.entries(entry.rules)) {
502
+ if (!isFields(result))
503
+ return undefined;
504
+ const findings = parseList(result.findings, parseFinding);
505
+ if (findings === undefined)
506
+ return undefined;
507
+ const { summary, hash } = result;
508
+ const marks = parseMarks(result.marks);
509
+ if (marks === undefined)
510
+ return undefined;
511
+ if (summary === undefined && hash === undefined) {
512
+ rules.set(key, { findings, ...marks });
513
+ }
514
+ else if (typeof summary === "string" && typeof hash === "string") {
515
+ rules.set(key, { findings, summary: summaryFromText(summary, hash), ...marks });
516
+ }
517
+ else {
518
+ return undefined;
519
+ }
520
+ }
521
+ return { fingerprint: entry.fingerprint, rules, reads: new Map(Object.entries(reads)) };
522
+ }
333
523
  /**
334
524
  * A cache read back from JSON. Anything that does not have the expected shape, or another format,
335
525
  * is an empty cache: a broken cache costs a cold run, never findings (workspace C35).
@@ -338,9 +528,28 @@ export function parseSnapshot(value) {
338
528
  const cache = emptyCache();
339
529
  if (!isFields(value) || value.format !== CACHE_FORMAT)
340
530
  return cache;
341
- const { files, projects, programs, verdicts } = value;
531
+ const { files, projects, programs, verdicts, analyses, run, used } = value;
342
532
  if (!isFields(files) || !isFields(projects) || !isFields(programs))
343
533
  return cache;
534
+ if (typeof run !== "number" || !Number.isSafeInteger(run) || !isFields(used))
535
+ return cache;
536
+ for (const [key, last] of Object.entries(used)) {
537
+ if (typeof last !== "number")
538
+ return emptyCache();
539
+ cache.used.set(key, last);
540
+ }
541
+ // A new run: what it uses is stamped with this number, what it does not keeps the older one.
542
+ cache.run = run + 1;
543
+ if (analyses !== undefined && !isFields(analyses))
544
+ return cache;
545
+ for (const [key, entry] of Object.entries(analyses ?? {})) {
546
+ if (!isFields(entry))
547
+ return emptyCache();
548
+ const { inputs, fingerprint } = entry;
549
+ if (typeof inputs !== "string" || typeof fingerprint !== "string")
550
+ return emptyCache();
551
+ cache.analyses.set(key, { inputs, fingerprint });
552
+ }
344
553
  if (verdicts !== undefined && !isFields(verdicts))
345
554
  return cache;
346
555
  for (const [key, verdict] of Object.entries(verdicts ?? {})) {
@@ -358,48 +567,28 @@ export function parseSnapshot(value) {
358
567
  cache.programs.set(tsconfig, parsed);
359
568
  }
360
569
  for (const [file, entry] of Object.entries(files)) {
361
- if (!isFields(entry) || typeof entry.fingerprint !== "string" || !isFields(entry.rules)) {
362
- return emptyCache();
363
- }
364
- const reads = stringRecord(entry.reads);
365
- if (reads === undefined)
570
+ const parsed = parseFileEntry(entry);
571
+ if (parsed === undefined)
366
572
  return emptyCache();
367
- const rules = new Map();
368
- for (const [key, result] of Object.entries(entry.rules)) {
369
- if (!isFields(result))
370
- return emptyCache();
371
- const findings = parseList(result.findings, parseFinding);
372
- if (findings === undefined)
373
- return emptyCache();
374
- const { summary, hash } = result;
375
- const marks = parseMarks(result.marks);
376
- if (marks === undefined)
377
- return emptyCache();
378
- if (summary === undefined && hash === undefined) {
379
- rules.set(key, { findings, ...marks });
380
- }
381
- else if (typeof summary === "string" && typeof hash === "string") {
382
- rules.set(key, { findings, summary: summaryFromText(summary, hash), ...marks });
383
- }
384
- else {
385
- return emptyCache();
386
- }
387
- }
388
- cache.files.set(file, {
389
- fingerprint: entry.fingerprint,
390
- rules,
391
- reads: new Map(Object.entries(reads)),
392
- });
573
+ cache.files.set(file, parsed);
393
574
  }
394
575
  for (const [key, entry] of Object.entries(projects)) {
395
576
  if (!isFields(entry) || typeof entry.inputs !== "string")
396
577
  return emptyCache();
397
578
  const findings = parseList(entry.findings, parseFinding);
398
579
  const marks = parseMarks(entry.marks);
580
+ const unstated = entry.unstated === undefined ? undefined : parseList(entry.unstated, parseUnstated);
399
581
  if (findings === undefined || marks === undefined)
400
582
  return emptyCache();
583
+ if (entry.unstated !== undefined && unstated === undefined)
584
+ return emptyCache();
401
585
  // The summaries are rebuilt from the file entries when the rule runs.
402
- cache.projects.set(key, { inputs: entry.inputs, findings, ...marks });
586
+ cache.projects.set(key, {
587
+ inputs: entry.inputs,
588
+ findings,
589
+ ...(unstated === undefined ? {} : { unstated }),
590
+ ...marks,
591
+ });
403
592
  }
404
593
  return cache;
405
594
  }
package/dist/checker.d.ts CHANGED
@@ -1,7 +1,8 @@
1
+ import type { MemoryPlan } from "./memory-plan.js";
1
2
  import type { ResultCache } from "./cache.js";
2
3
  import type { TimingRecorder } from "./timing.js";
3
- import type { CheckProgress } from "./engine.js";
4
- import type { CheckResult, Config, EditorAction, EditorHint, Finding, FixForm, FixReview, FixSetReview, LibraryUse, Location, StatedGuarantee, RuleSelection, TokenType } from "./types.js";
4
+ import type { CheckerSlicing, CheckProgress } from "./engine.js";
5
+ import type { CheckResult, Config, EditorAction, EditorHint, Finding, FixForm, FixReview, FixSetReview, LibraryUse, Location, StatedGuarantee, RuleSelection, TokenType, ReportOutput, ReportPlace } from "./types.js";
5
6
  export type CheckInput = {
6
7
  config: Config;
7
8
  cwd: string;
@@ -49,6 +50,13 @@ export type SlicedCheck = {
49
50
  };
50
51
  /** The default slice: short against the editor's 200 ms budget, long against a pause's cost. */
51
52
  export declare const SLICE_MS = 20;
53
+ /** A memory budget for `createChecker` (`memory`). */
54
+ export type MemoryBudget = {
55
+ readonly mb: number;
56
+ readonly planned?: (plan: Extract<MemoryPlan, {
57
+ kind: "fits";
58
+ }>) => void;
59
+ };
52
60
  /** One config's checker: it keeps its programs between runs, so a later run only redoes what changed. */
53
61
  export type Checker = {
54
62
  /** Reuses the previous run's programs as `oldProgram`. */
@@ -107,6 +115,11 @@ export type Checker = {
107
115
  * before a check. Pair them with that check's findings with `proveGuarantees`.
108
116
  */
109
117
  guarantees(): readonly StatedGuarantee[];
118
+ /**
119
+ * Runs the report `report` of `plugin` (`Plugin.reports`) on the summaries of the last full
120
+ * check; undefined when that plugin has no such report.
121
+ */
122
+ report(plugin: string, report: string, place: (location: Location) => ReportPlace): ReportOutput | undefined;
110
123
  /**
111
124
  * Tries each fix of `findings` on a copy of the code of the last run (fixes.ts) and returns the
112
125
  * findings in the same order, each with only the fixes that compile. Verdicts are kept in the
@@ -134,7 +147,7 @@ export type Checker = {
134
147
  * Editor requests are answered from the programs of the last check. A plugin that throws
135
148
  * propagates the error: the language server is the boundary that logs it.
136
149
  */
137
- export declare function createChecker({ config, cwd, rules, cache, uncapped, ignores, timing, retainPrograms, }: {
150
+ export declare function createChecker({ config, cwd, rules, cache, uncapped, ignores, timing, retainPrograms, slicing, memory, }: {
138
151
  config: Config;
139
152
  cwd: string;
140
153
  rules?: RuleSelection;
@@ -158,6 +171,18 @@ export declare function createChecker({ config, cwd, rules, cache, uncapped, ign
158
171
  * programs afterwards: a later request (a fix tried, a hover) builds them again.
159
172
  */
160
173
  retainPrograms?: false;
174
+ /**
175
+ * Starts a new type checker every so many files of a project (`CheckerSlicing`). Not a config
176
+ * key: for stateward's own tests. Wins over the slicing `memory` plans.
177
+ */
178
+ slicing?: CheckerSlicing;
179
+ /**
180
+ * A memory budget each full check plans for (`memory-plan.ts`): from the size of the programs,
181
+ * before building them, how many files share one type checker. `planned` is told the plan
182
+ * before the check starts. A budget below what parsing and binding needs throws
183
+ * `MemoryBudgetError`, before anything is built.
184
+ */
185
+ memory?: MemoryBudget;
161
186
  }): Checker;
162
187
  /** One run with a fresh checker. */
163
188
  export declare function check({ config, cwd, overlays, rules, cache, uncapped, ignores, }: CheckInput): CheckResult;
package/dist/checker.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { createBackend, toTypeScriptPath } from "./backend/typescript6.js";
2
+ import { displayPath } from "./display-path.js";
3
+ import { MemoryBudgetError, planMemory } from "./memory-plan.js";
2
4
  import { emptyCache } from "./cache.js";
3
5
  import { reviewFixes, verifyFixSet } from "./fixes.js";
4
6
  import { legacyMarkerRewrite } from "./guarantee-markers.js";
5
7
  import { ledgerGuarantees } from "./ledger.js";
6
8
  import { unlistedGuarantees } from "./stated.js";
7
- import { drain, filePhaseRun, needsJsDoc, projectPhaseSteps, projectRuleIds, ruleOffAtFn, runFileRules, silentReasons, } from "./engine.js";
9
+ import { builtSources, drain, filePhaseRun, needsJsDoc, projectPhaseSteps, projectRuleIds, ruleOffAtFn, runFileRules, silentReasons, } from "./engine.js";
8
10
  /** The default slice: short against the editor's 200 ms budget, long against a pause's cost. */
9
11
  export const SLICE_MS = 20;
10
12
  function fileTotal(units) {
@@ -14,6 +16,23 @@ function fileTotal(units) {
14
16
  function pause() {
15
17
  return new Promise((resolve) => setImmediate(resolve));
16
18
  }
19
+ /**
20
+ * The slicing the budget's plan asks for (undefined when every project keeps one checker), after
21
+ * telling `planned`; throws `MemoryBudgetError` when the budget is below the plan's floor.
22
+ */
23
+ function budgetSlicing(cwd, memory, pending, keepsPrograms) {
24
+ const plan = planMemory(memory.mb, pending.map((unit) => ({ tsconfig: unit.tsconfig, size: unit.size() })), keepsPrograms);
25
+ if (plan.kind === "below-floor") {
26
+ throw new MemoryBudgetError(plan, displayPath(cwd, plan.tsconfig));
27
+ }
28
+ memory.planned?.(plan);
29
+ const perChecker = new Map(plan.projects
30
+ .filter((project) => project.slices > 1)
31
+ .map((project) => [project.tsconfig, project.filesPerChecker]));
32
+ return perChecker.size === 0
33
+ ? undefined
34
+ : { filesPerChecker: (tsconfig) => perChecker.get(tsconfig) };
35
+ }
17
36
  /** The own files by name, for editor requests; binds each program, as plugins walk the nodes. */
18
37
  function index(units) {
19
38
  for (const unit of units)
@@ -27,7 +46,7 @@ function index(units) {
27
46
  * Editor requests are answered from the programs of the last check. A plugin that throws
28
47
  * propagates the error: the language server is the boundary that logs it.
29
48
  */
30
- export function createChecker({ config, cwd, rules = { kind: "configured" }, cache = emptyCache(), uncapped, ignores, timing, retainPrograms, }) {
49
+ export function createChecker({ config, cwd, rules = { kind: "configured" }, cache = emptyCache(), uncapped, ignores, timing, retainPrograms, slicing, memory, }) {
31
50
  const backend = createBackend({
32
51
  config,
33
52
  cwd,
@@ -59,27 +78,32 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
59
78
  const started = performance.now();
60
79
  timing?.start();
61
80
  known = undefined;
81
+ const pending = backend.pending(overlays);
82
+ const keepsPrograms = retainPrograms !== false;
83
+ const planned = memory === undefined ? undefined : budgetSlicing(cwd, memory, pending, keepsPrograms);
62
84
  const opened = () => {
63
- const units = backend.open(overlays);
85
+ const units = pending.map((unit) => unit.open());
64
86
  timing?.program(performance.now() - started);
65
87
  return units;
66
88
  };
67
89
  const startFilePhase = (units) => {
68
- filePhase = filePhaseRun(config, cwd, units, rules, cache === false ? undefined : cache, ignores !== false, timing);
90
+ filePhase = filePhaseRun(config, cwd, units, rules, cache === false ? undefined : cache, ignores !== false, timing, slicing ?? planned);
69
91
  return filePhase;
70
92
  };
71
93
  let phase;
72
- if (retainPrograms === false) {
73
- // No variable holds the units here: once the file phase returns they can be collected.
94
+ if (!keepsPrograms) {
95
+ // One project at a time: the file phase builds each program when it reaches it and lets
96
+ // it go after its files, so the largest program is held, not all of them. No variable
97
+ // holds a unit here.
74
98
  lastUnits = undefined;
75
- phase = yield* startFilePhase(opened()).steps;
99
+ phase = yield* startFilePhase(pending).steps;
76
100
  backend.release();
77
101
  }
78
102
  else {
79
103
  lastUnits = opened();
80
104
  // Building the programs is a step of its own, so its cost is told apart from a rule's.
81
105
  yield { phase: "files", done: 0, total: fileTotal(lastUnits) };
82
- phase = yield* startFilePhase(lastUnits).steps;
106
+ phase = yield* startFilePhase(builtSources(lastUnits)).steps;
83
107
  }
84
108
  filePhase = undefined;
85
109
  const kept = new Map();
@@ -167,6 +191,16 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
167
191
  const known = [...listed, ...unlistedGuarantees(stated, listed)];
168
192
  return [...known, ...ledgerGuarantees(ledgerRefs, known, tagRules)];
169
193
  },
194
+ report(pluginName, reportName, place) {
195
+ const plugin = config.plugins.find((one) => one.name === pluginName);
196
+ const reports = plugin?.reports;
197
+ if (reports === undefined || !Object.hasOwn(reports, reportName))
198
+ return undefined;
199
+ return reports[reportName]?.run({
200
+ projectSummaries: (ruleId) => summaries.get(ruleId)?.(),
201
+ place,
202
+ });
203
+ },
170
204
  reviewFixes(findings) {
171
205
  const units = (lastUnits ??= backend.open(new Map()));
172
206
  return reviewFixes(findings, units, cache === false ? localVerdicts : cache);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * How a class is named across packs: by the language, never by a library. A class of the project
3
+ * is its declaration's symbol id; a class of the platform (TypeScript's lib, a global in a
4
+ * declaration file) is `builtin:<Name>`; a package's class is `package:<name>#<Class>`, the same
5
+ * from its types, its source and the config. The errors pack's `errors/throws` names classes so,
6
+ * and a pack that reads it names the classes in its own code with `classIdOf`.
7
+ */
8
+ import ts from "typescript";
9
+ import type { TypeQueries } from "./types.js";
10
+ /** A declaration of the platform: TypeScript's lib, or a global in a declaration file. */
11
+ export declare function isPlatformDeclaration(node: ts.Node, file: string): boolean;
12
+ /**
13
+ * The package a file outside the project belongs to: by its node_modules folder, or, for a
14
+ * package linked from elsewhere (a workspace package, whose real path has no node_modules), by
15
+ * the name in its package.json.
16
+ */
17
+ export declare function packageNameOf(types: Pick<TypeQueries, "packageOf">, file: string): string | undefined;
18
+ /**
19
+ * The package a declaration outside the project belongs to: the `declare module "x"` it sits in,
20
+ * by the name it is written with, else its file's package (`packageNameOf`); undefined when
21
+ * neither names one.
22
+ */
23
+ export declare function declaredPackageOf(types: Pick<TypeQueries, "packageOf">, declaration: {
24
+ readonly file: string;
25
+ readonly node: ts.Node;
26
+ }): string | undefined;
27
+ /**
28
+ * The id of the class a name refers to (`X` in `throw new X()`, `ns.X`, `@Catch(X)`):
29
+ * `builtin:<Name>` for a class of the platform, `package:<name>#<Class>` for a package's class,
30
+ * the symbol id (`SymbolRef.id`) for a class of the project. Undefined when the name resolves to
31
+ * nothing, or to a declaration outside the project whose package is not known.
32
+ */
33
+ export declare function classIdOf(types: TypeQueries, node: ts.Node): string | undefined;
34
+ //# sourceMappingURL=class-id.d.ts.map