@stateward/core 1.0.1 → 1.1.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.
@@ -1,10 +1,10 @@
1
1
  import path from "node:path";
2
2
  import picomatch from "picomatch";
3
3
  import ts from "typescript";
4
- import { computeFingerprints, packageDependencies, packageEntries, packageManifests, packageNames, textHash, } from "./fingerprints.js";
4
+ import { computeFingerprints, declarationTextHash, packageDependencies, packageEntries, packageManifests, packageNames, } from "./fingerprints.js";
5
5
  import { markedComments } from "./comments.js";
6
6
  import { recordInputs, recordingHost, replays } from "./program-record.js";
7
- import { declarationPath } from "./qualified-ids.js";
7
+ import { declarationAtPath, declarationPath } from "./qualified-ids.js";
8
8
  import { displayPath } from "../display-path.js";
9
9
  import { expandTsconfigs } from "../tsconfigs.js";
10
10
  /** The tsconfig could not be read or is invalid. */
@@ -300,9 +300,16 @@ function tryEditsOn(program, host, candidates) {
300
300
  const ranges = new Map();
301
301
  /** Per edited file, the edits placed in it and how an offset of the old text moves. */
302
302
  const moves = new Map();
303
+ /** Files a fix creates: edits at the start of a file that does not exist yet. */
304
+ const created = new Set();
303
305
  for (const [file, placed] of byFile) {
304
306
  const sourceFile = program.getSourceFile(file);
305
- const text = sourceFile?.text;
307
+ const creates = sourceFile === undefined &&
308
+ !host.fileExists(file) &&
309
+ placed.every(({ edit: { location } }) => location.start === 0 && location.end === 0);
310
+ if (creates)
311
+ created.add(file);
312
+ const text = creates ? "" : sourceFile?.text;
306
313
  const fits = placed.every(({ edit: { location } }) => text !== undefined &&
307
314
  location.start >= 0 &&
308
315
  location.start <= location.end &&
@@ -378,6 +385,18 @@ function tryEditsOn(program, host, candidates) {
378
385
  for (const [file, spans] of ranges) {
379
386
  const before = program.getSourceFile(file);
380
387
  const after = copy.getSourceFile(file);
388
+ if (created.has(file) && after !== undefined) {
389
+ // Every error in a file the fix writes is the fix's own.
390
+ const [error] = errorsOf(copy, after);
391
+ if (error === undefined)
392
+ continue;
393
+ for (const { candidate } of spans) {
394
+ if (verdicts[candidate]?.kind === "compiles") {
395
+ verdicts[candidate] = { kind: "breaks", error: firstLine(error) };
396
+ }
397
+ }
398
+ continue;
399
+ }
381
400
  if (before === undefined || after === undefined)
382
401
  continue;
383
402
  // A fix that changes a declaration's type answers for every line of the files it edits.
@@ -474,6 +493,34 @@ function unresolvedImportsOf(program, file) {
474
493
  }
475
494
  return found;
476
495
  }
496
+ /** Whether a project with these options checks with `strictNullChecks` (TypeScript 6: on unless turned off). */
497
+ export function checksNulls(options) {
498
+ return options.strictNullChecks ?? options.strict ?? true;
499
+ }
500
+ const TYPED_EXTENSIONS = new Set([
501
+ ts.Extension.Dts,
502
+ ts.Extension.Dmts,
503
+ ts.Extension.Dcts,
504
+ ts.Extension.Ts,
505
+ ts.Extension.Tsx,
506
+ ts.Extension.Mts,
507
+ ts.Extension.Cts,
508
+ ]);
509
+ /** `ProjectUnit.typesResolve` for a project, remembered by module name. */
510
+ function typesResolver(tsconfig, options) {
511
+ const known = new Map();
512
+ // A file that need not exist: resolution only looks at its folder and above.
513
+ const from = path.join(path.dirname(tsconfig), "__stateward_types__.ts");
514
+ return (module) => {
515
+ const before = known.get(module);
516
+ if (before !== undefined)
517
+ return before;
518
+ const resolved = ts.resolveModuleName(module, from, options, ts.sys).resolvedModule;
519
+ const typed = resolved !== undefined && TYPED_EXTENSIONS.has(resolved.extension);
520
+ known.set(module, typed);
521
+ return typed;
522
+ };
523
+ }
477
524
  function firstSyntaxError(program, file) {
478
525
  const sourceFile = program.getSourceFile(file);
479
526
  if (sourceFile === undefined)
@@ -625,6 +672,21 @@ shared = isLibraryFile) {
625
672
  },
626
673
  };
627
674
  }
675
+ /**
676
+ * The host a recorded program is replayed against: the disk, with `overlays` in front of it as
677
+ * `hostWithOverlays` serves them (an overlay exists, and its text is what is read), so a replay
678
+ * answers as the build it stands for would have.
679
+ */
680
+ function replayHost(options, overlays) {
681
+ const base = ts.createCompilerHost(options, false);
682
+ if (overlays.size === 0)
683
+ return base;
684
+ return {
685
+ ...base,
686
+ fileExists: (fileName) => overlays.has(fileName) || base.fileExists(fileName),
687
+ readFile: (fileName) => overlays.get(fileName) ?? base.readFile(fileName),
688
+ };
689
+ }
628
690
  function matcher(patterns) {
629
691
  if (patterns.length === 0)
630
692
  return () => false;
@@ -731,6 +793,54 @@ function isPromiseType(checker, type) {
731
793
  return awaited !== undefined && awaited !== type;
732
794
  }
733
795
  const NULLISH = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
796
+ /** The property a stated guarantee is written in (`TypeQueries.guaranteesOf`). */
797
+ const GUARANTEE_PROPERTY = "__guarantee";
798
+ /** The guarantee names of one type that is not a union: its optional `__guarantee` literals. */
799
+ function memberGuarantees(checker, type) {
800
+ const property = checker.getPropertyOfType(type, GUARANTEE_PROPERTY);
801
+ if (property === undefined || !(property.flags & ts.SymbolFlags.Optional))
802
+ return [];
803
+ const value = checker.getTypeOfSymbol(property);
804
+ const names = [];
805
+ for (const part of value.isUnion() ? value.types : [value]) {
806
+ if (part.flags & NULLISH)
807
+ continue;
808
+ if (!part.isStringLiteral())
809
+ return [];
810
+ names.push(part.value);
811
+ }
812
+ return names;
813
+ }
814
+ /**
815
+ * The guarantees every member of `type` states (`null` and `undefined` left out), sorted. A
816
+ * member that states none makes the whole type state none.
817
+ */
818
+ function guaranteesOfType(checker, found) {
819
+ const type = widened(checker, found);
820
+ if (type === undefined)
821
+ return [];
822
+ const members = (type.isUnion() ? type.types : [type]).filter((member) => (member.flags & NULLISH) === 0);
823
+ let shared;
824
+ for (const member of members) {
825
+ const names = memberGuarantees(checker, member);
826
+ shared = shared === undefined ? [...names] : shared.filter((name) => names.includes(name));
827
+ if (shared.length === 0)
828
+ return [];
829
+ }
830
+ return [...new Set(shared ?? [])].sort();
831
+ }
832
+ /** The declared type of a declaration: a variable's or property's type, or a type alias's. */
833
+ function declaredTypeOf(checker, declaration) {
834
+ const name = ts.isDeclarationStatement(declaration) || ts.isVariableDeclaration(declaration)
835
+ ? ts.getNameOfDeclaration(declaration)
836
+ : undefined;
837
+ const symbol = name === undefined ? undefined : checker.getSymbolAtLocation(name);
838
+ if (symbol === undefined)
839
+ return checker.getTypeAtLocation(declaration);
840
+ return symbol.flags & ts.SymbolFlags.Value
841
+ ? checker.getTypeOfSymbol(symbol)
842
+ : checker.getDeclaredTypeOfSymbol(symbol);
843
+ }
734
844
  /** A string, number or boolean literal, or an enum member: a type with exactly one value. */
735
845
  function isUnitLiteral(type) {
736
846
  return (type.isStringLiteral() ||
@@ -985,6 +1095,49 @@ function isReadonlyProperty(owner, property) {
985
1095
  return (declarations.length > 0 &&
986
1096
  declarations.every((declaration) => (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly) !== 0));
987
1097
  }
1098
+ /** An object type with an `aborted: boolean` property: `AbortSignal`, or a library's own signal type. */
1099
+ function isSignal(checker, type) {
1100
+ const members = withoutNullish(type);
1101
+ return (members.length > 0 &&
1102
+ members.every((member) => {
1103
+ if (!(member.flags & ts.TypeFlags.Object))
1104
+ return false;
1105
+ const aborted = checker.getPropertyOfType(member, "aborted");
1106
+ if (aborted === undefined)
1107
+ return false;
1108
+ const value = checker.getTypeOfSymbol(aborted);
1109
+ return withoutNullish(value).every((part) => (part.flags & ts.TypeFlags.BooleanLike) !== 0);
1110
+ }));
1111
+ }
1112
+ /** Where the callee takes a signal: a parameter that is one, or an options object holding one. */
1113
+ function signalParameter(checker, call) {
1114
+ const signature = checker.getResolvedSignature(call);
1115
+ if (signature === undefined)
1116
+ return undefined;
1117
+ for (const [index, parameter] of signature.parameters.entries()) {
1118
+ const declared = parameter.valueDeclaration;
1119
+ if (declared !== undefined &&
1120
+ ts.isParameter(declared) &&
1121
+ declared.dotDotDotToken !== undefined) {
1122
+ return undefined;
1123
+ }
1124
+ const type = widened(checker, checker.getTypeOfSymbol(parameter));
1125
+ if (type === undefined)
1126
+ continue;
1127
+ if (isSignal(checker, type))
1128
+ return { index, property: undefined };
1129
+ // An options object you fill in; a `Request`, which carries its own readonly signal, is not one.
1130
+ const holds = withoutNullish(type).some((member) => {
1131
+ const signal = checker.getPropertyOfType(member, "signal");
1132
+ return (signal !== undefined &&
1133
+ !isReadonlyProperty(member, signal) &&
1134
+ isSignal(checker, checker.getTypeOfSymbol(signal)));
1135
+ });
1136
+ if (holds)
1137
+ return { index, property: "signal" };
1138
+ }
1139
+ return undefined;
1140
+ }
988
1141
  function withoutNullish(type) {
989
1142
  const nothing = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
990
1143
  return (type.isUnion() ? type.types : [type]).filter((member) => !(member.flags & nothing));
@@ -1312,6 +1465,14 @@ root, packageOf, isEntry, dependenciesOf) {
1312
1465
  }
1313
1466
  return [...files].sort();
1314
1467
  },
1468
+ guaranteesOf(target) {
1469
+ const checker = typeChecker();
1470
+ if ("kind" in target)
1471
+ return guaranteesOfType(checker, checker.getTypeAtLocation(target));
1472
+ const declaration = declarations.get(target.id);
1473
+ const type = declaration === undefined ? undefined : declaredTypeOf(checker, declaration);
1474
+ return type === undefined ? [] : guaranteesOfType(checker, type);
1475
+ },
1315
1476
  awaitedAliasOf(node) {
1316
1477
  return aliasOfType(typeChecker(), typeChecker().getTypeAtLocation(node));
1317
1478
  },
@@ -1478,6 +1639,9 @@ root, packageOf, isEntry, dependenciesOf) {
1478
1639
  calleeTags(call) {
1479
1640
  return calleeTags(typeChecker(), call);
1480
1641
  },
1642
+ signalParameterOf(call) {
1643
+ return signalParameter(typeChecker(), call);
1644
+ },
1481
1645
  narrowedBy(reference, test) {
1482
1646
  return narrowedMembers(program, typeChecker(), reference, test);
1483
1647
  },
@@ -1609,8 +1773,10 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1609
1773
  if (missingLib !== undefined)
1610
1774
  throw new TypeScriptLibMissingError(missingLib);
1611
1775
  // Only a program built from nothing asks the host every question; one built on an old
1612
- // program, or on unsaved text, is not recorded.
1613
- const queries = cache !== undefined && oldProgram === undefined && overlays.size === 0 && !trustCache
1776
+ // program is not recorded. One built on unsaved text is: its answers are the overlays', and a
1777
+ // replay serves the overlays of its own run the same way (`replayHost`), so the record holds
1778
+ // exactly while the open documents have that text (an editor's next start).
1779
+ const queries = cache !== undefined && oldProgram === undefined && !trustCache
1614
1780
  ? new Map()
1615
1781
  : undefined;
1616
1782
  const plainHost = hostWithOverlays(parsed.options, overlays, sources, trustCache, jsDoc);
@@ -1652,9 +1818,26 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1652
1818
  }
1653
1819
  return fingerprints;
1654
1820
  };
1655
- /** What each file's rules were handed, by file. */
1821
+ /** What each file's rules were handed, by file: read ids, with the file each one is in. */
1656
1822
  const reads = new Map();
1657
1823
  const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf);
1824
+ const idFileName = idFileNames(cwd);
1825
+ const fileId = (fileName) => `${idFileName(fileName)}#`;
1826
+ /** The read id of a declaration handed out: its own id when that finds it again, else its file's. */
1827
+ const readId = (symbol, found) => {
1828
+ if (!types.isOwnFile(found.file) || ts.isSourceFile(found.node))
1829
+ return fileId(found.file);
1830
+ const sourceFile = program.getSourceFile(found.file);
1831
+ const at = symbol.id.indexOf("#");
1832
+ return sourceFile !== undefined &&
1833
+ at >= 0 &&
1834
+ symbol.id.slice(0, at + 1) === fileId(found.file) &&
1835
+ declarationAtPath(sourceFile, symbol.id.slice(at + 1)) === found.node
1836
+ ? symbol.id
1837
+ : fileId(found.file);
1838
+ };
1839
+ /** Read prints computed in this program, by read id. */
1840
+ const prints = new Map();
1658
1841
  const unit = {
1659
1842
  tsconfig: tsconfigPath,
1660
1843
  files,
@@ -1663,29 +1846,46 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1663
1846
  types,
1664
1847
  fingerprint: (file) => fingerprintsOf().get(file),
1665
1848
  typesFor: (file) => {
1666
- const read = reads.get(file) ?? new Set();
1849
+ const read = reads.get(file) ?? new Map();
1667
1850
  reads.set(file, read);
1668
1851
  return {
1669
1852
  ...types,
1670
1853
  declarationOf(symbol) {
1671
1854
  const found = types.declarationOf(symbol);
1672
- if (found !== undefined && found.file !== file)
1673
- read.add(found.file);
1855
+ if (found !== undefined && found.file !== file) {
1856
+ read.set(readId(symbol, found), found.file);
1857
+ }
1674
1858
  return found;
1675
1859
  },
1676
1860
  };
1677
1861
  },
1678
- readsOf: (file) => [...(reads.get(file) ?? [])].sort(),
1679
- readFingerprint: (file) => {
1680
- const sourceFile = program.getSourceFile(file);
1681
- if (sourceFile === undefined)
1682
- return undefined;
1683
- const print = textHash(sourceFile);
1684
- readPrints[file] = print;
1862
+ readsOf: (file, mentioned) => {
1863
+ const ids = new Set();
1864
+ for (const [id, readFile] of reads.get(file) ?? []) {
1865
+ ids.add(mentioned(readFile) ? fileId(readFile) : id);
1866
+ }
1867
+ return [...ids].sort();
1868
+ },
1869
+ readFingerprint: (read) => {
1870
+ if (prints.has(read))
1871
+ return prints.get(read);
1872
+ const at = read.indexOf("#");
1873
+ const sourceFile = at < 0
1874
+ ? undefined
1875
+ : program.getSourceFile(toTypeScriptPath(path.resolve(cwd, read.slice(0, at))));
1876
+ const node = sourceFile === undefined ? undefined : declarationAtPath(sourceFile, read.slice(at + 1));
1877
+ const print = sourceFile === undefined || node === undefined
1878
+ ? undefined
1879
+ : declarationTextHash(sourceFile, node);
1880
+ prints.set(read, print);
1881
+ if (print !== undefined)
1882
+ readPrints[read] = print;
1685
1883
  return print;
1686
1884
  },
1687
1885
  syntaxError: (file) => firstSyntaxError(program, file),
1688
1886
  unresolvedImports: (file) => unresolvedImportsOf(program, file),
1887
+ strictNullChecks: checksNulls(parsed.options),
1888
+ typesResolve: typesResolver(tsconfigPath, parsed.options),
1689
1889
  bind: () => {
1690
1890
  program.getTypeChecker();
1691
1891
  },
@@ -1705,9 +1905,9 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1705
1905
  * now: its files and fingerprints come from the record, and the program is built only if
1706
1906
  * something asks for a node or a type.
1707
1907
  */
1708
- const recordedUnit = (project, claimed, record) => {
1908
+ const recordedUnit = (project, claimed, record, overlays) => {
1709
1909
  let built;
1710
- const real = () => (built ??= buildUnit(project, claimed, new Map(), false));
1910
+ const real = () => (built ??= buildUnit(project, claimed, overlays, false));
1711
1911
  return {
1712
1912
  tsconfig: project.tsconfigPath,
1713
1913
  files: record.files,
@@ -1718,11 +1918,13 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1718
1918
  },
1719
1919
  fingerprint: (file) => record.fingerprints[file],
1720
1920
  typesFor: (file) => real().typesFor(file),
1721
- readsOf: (file) => (built === undefined ? [] : built.readsOf(file)),
1921
+ readsOf: (file, mentioned) => (built === undefined ? [] : built.readsOf(file, mentioned)),
1722
1922
  // The program is the recorded one: a text hash it recorded is the answer.
1723
1923
  readFingerprint: (file) => record.reads[file] ?? real().readFingerprint(file),
1724
1924
  syntaxError: (file) => real().syntaxError(file),
1725
1925
  unresolvedImports: (file) => real().unresolvedImports(file),
1926
+ strictNullChecks: checksNulls(project.parsed.options),
1927
+ typesResolve: typesResolver(project.tsconfigPath, project.parsed.options),
1726
1928
  bind: () => {
1727
1929
  real().bind();
1728
1930
  },
@@ -1738,13 +1940,12 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1738
1940
  const record = cache?.programs.get(project.tsconfigPath);
1739
1941
  const replayable = record !== undefined &&
1740
1942
  !previous.has(project.tsconfigPath) &&
1741
- normalized.size === 0 &&
1742
1943
  !trustCache &&
1743
1944
  record.inputs ===
1744
1945
  recordInputs(programInputs(project.parsed, claimed), project.parsed.options) &&
1745
- replays(record.queries, ts.createCompilerHost(project.parsed.options, false));
1946
+ replays(record.queries, replayHost(project.parsed.options, normalized));
1746
1947
  return replayable
1747
- ? recordedUnit(project, claimed, record)
1948
+ ? recordedUnit(project, claimed, record, normalized)
1748
1949
  : buildUnit(project, claimed, normalized, trustCache);
1749
1950
  });
1750
1951
  };
package/dist/cache.d.ts CHANGED
@@ -5,7 +5,7 @@ import type { Finding, FixVerdict, Json, Rule, Severity } from "./types.js";
5
5
  *
6
6
  * - per own file, under its dependency fingerprint (backend/fingerprints.ts), and per rule under
7
7
  * its rule key (`ruleKey`): the findings the rule reported on that file, and a project rule's
8
- * summary; with the full fingerprint of each other file whose syntax the rules read there. A
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
10
  * - per project rule, under its rule key: a hash of all its summaries, and the findings its check
11
11
  * produced from them. Equal summaries give equal findings (a project rule decides from its
@@ -16,7 +16,7 @@ import type { Finding, FixVerdict, Json, Rule, Severity } from "./types.js";
16
16
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
17
17
  */
18
18
  /** Bumped whenever what is stored, or how a key is computed, changes. */
19
- export declare const CACHE_FORMAT = 5;
19
+ export declare const CACHE_FORMAT = 7;
20
20
  /**
21
21
  * A project rule's summary of one file: the hash of its JSON text, and either that text or, once a
22
22
  * rule or a hover needed the value (a run whose summaries are all unchanged never does), the parsed
@@ -56,8 +56,9 @@ export type FileEntry = {
56
56
  fingerprint: string;
57
57
  rules: ReadonlyMap<string, RuleResult>;
58
58
  /**
59
- * The other files whose syntax the rules read on this file (`TypeQueries.declarationOf`), with
60
- * each one's full fingerprint then: the entry holds while each is the same.
59
+ * What the rules on this file read of other files (`TypeQueries.declarationOf`), by read id (a
60
+ * declaration's qualified id, or a file's own id `src/a.ts#` for its whole text:
61
+ * `ProjectUnit.readsOf`), with each one's hash then: the entry holds while each is the same.
61
62
  */
62
63
  reads: ReadonlyMap<string, string>;
63
64
  };
package/dist/cache.js CHANGED
@@ -5,7 +5,7 @@ import { isQueryKind } from "./backend/program-record.js";
5
5
  *
6
6
  * - per own file, under its dependency fingerprint (backend/fingerprints.ts), and per rule under
7
7
  * its rule key (`ruleKey`): the findings the rule reported on that file, and a project rule's
8
- * summary; with the full fingerprint of each other file whose syntax the rules read there. A
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
10
  * - per project rule, under its rule key: a hash of all its summaries, and the findings its check
11
11
  * produced from them. Equal summaries give equal findings (a project rule decides from its
@@ -16,7 +16,7 @@ import { isQueryKind } from "./backend/program-record.js";
16
16
  * server save it to disk between runs as a `CacheSnapshot` (disk-cache.ts).
17
17
  */
18
18
  /** Bumped whenever what is stored, or how a key is computed, changes. */
19
- export const CACHE_FORMAT = 5;
19
+ export const CACHE_FORMAT = 7;
20
20
  /** Frozen all the way down: a cached summary is shared between runs, so no rule may change it. */
21
21
  function deepFreeze(value) {
22
22
  if (typeof value === "object" && value !== null) {
package/dist/checker.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { ResultCache } from "./cache.js";
2
2
  import type { TimingRecorder } from "./timing.js";
3
3
  import type { CheckProgress } from "./engine.js";
4
- import type { CheckResult, Config, EditorAction, EditorHint, Finding, FixForm, FixReview, FixSetReview, LibraryUse, Location, RuleSelection, TokenType } from "./types.js";
4
+ import type { CheckResult, Config, EditorAction, EditorHint, Finding, FixForm, FixReview, FixSetReview, LibraryUse, Location, StatedGuarantee, RuleSelection, TokenType } from "./types.js";
5
5
  export type CheckInput = {
6
6
  config: Config;
7
7
  cwd: string;
@@ -65,8 +65,14 @@ export type Checker = {
65
65
  * The fast pass: runs only the file rules, only on `files` (own files; others are ignored), on
66
66
  * programs that reuse the previous ones. Findings are for those files only; project rules do not
67
67
  * run, so their findings are the last `check`'s.
68
+ *
69
+ * The rules run on each file, unless it is in `reusable` and the checker's cache holds its
70
+ * results under its current dependency fingerprint and reads (as a full check would reuse them):
71
+ * then they are taken from there. The fast pass never writes the cache. Name only files that are
72
+ * likely unchanged (an editor's document just opened): the first such question computes the
73
+ * fingerprints of the whole program, which the next full check reuses.
68
74
  */
69
- checkFiles(files: readonly string[], overlays?: ReadonlyMap<string, string>): CheckResult;
75
+ checkFiles(files: readonly string[], overlays?: ReadonlyMap<string, string>, reusable?: readonly string[]): CheckResult;
70
76
  /** Ids of the active project rules, whose findings only `check` produces. */
71
77
  readonly projectRuleIds: ReadonlySet<string>;
72
78
  /**
@@ -95,6 +101,12 @@ export type Checker = {
95
101
  * from the last full check: `stateward deps`. Empty before a check.
96
102
  */
97
103
  libraryFacts(): readonly LibraryUse[];
104
+ /**
105
+ * The guarantees stated in the project, as the plugins that prove them read them
106
+ * (`EditorContributions.guarantees`), from the last full check: no new type checking. Empty
107
+ * before a check. Pair them with that check's findings with `proveGuarantees`.
108
+ */
109
+ guarantees(): readonly StatedGuarantee[];
98
110
  /**
99
111
  * Tries each fix of `findings` on a copy of the code of the last run (fixes.ts) and returns the
100
112
  * findings in the same order, each with only the fixes that compile. Verdicts are kept in the
package/dist/checker.js CHANGED
@@ -109,12 +109,14 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
109
109
  sliceStarted = performance.now();
110
110
  }
111
111
  },
112
- checkFiles(files, overlays = new Map()) {
112
+ checkFiles(files, overlays = new Map(), reusable = []) {
113
113
  const started = performance.now();
114
114
  const units = backend.reopen(overlays);
115
115
  lastUnits = units;
116
116
  known = undefined;
117
- return runFileRules(config, cwd, units, new Set(files.map(toTypeScriptPath)), started, uncapped === undefined, ignores !== false);
117
+ return runFileRules(config, cwd, units, new Set(files.map(toTypeScriptPath)), started, uncapped === undefined, ignores !== false, cache === false || reusable.length === 0
118
+ ? undefined
119
+ : { cache, files: new Set(reusable.map(toTypeScriptPath)) });
118
120
  },
119
121
  // Read on demand: it consults the rollout file, which a run that ignores rollout
120
122
  // (`plan`, `check --rule`) must not touch.
@@ -143,6 +145,11 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
143
145
  projectSummaries: (ruleId) => summaries.get(ruleId)?.(),
144
146
  }) ?? []);
145
147
  },
148
+ guarantees() {
149
+ return config.plugins.flatMap((plugin) => plugin.editor?.guarantees?.({
150
+ projectSummaries: (ruleId) => summaries.get(ruleId)?.(),
151
+ }) ?? []);
152
+ },
146
153
  reviewFixes(findings) {
147
154
  const units = (lastUnits ??= backend.open(new Map()));
148
155
  return reviewFixes(findings, units, cache === false ? localVerdicts : cache);
@@ -179,13 +186,24 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
179
186
  hint: action.title,
180
187
  location: { file, start, end },
181
188
  related: [],
182
- fixes: [{ title: action.title, edits: action.edits }],
189
+ fixes: [
190
+ {
191
+ title: action.title,
192
+ edits: action.edits,
193
+ alternatives: (action.alternatives ?? []).map((form) => ({
194
+ title: action.title,
195
+ edits: form.edits,
196
+ })),
197
+ },
198
+ ],
183
199
  }));
184
200
  const units = (lastUnits ??= backend.open(new Map()));
185
201
  const reviews = reviewFixes(findings, units, cache === false ? localVerdicts : cache);
186
- return offered.filter((_, i) => {
202
+ // Each action as the first of its forms that compiles.
203
+ return offered.flatMap((action, i) => {
187
204
  const reviewed = reviews[i]?.finding;
188
- return reviewed?.kind === "problem" && reviewed.fixes.length > 0;
205
+ const form = reviewed?.kind === "problem" ? reviewed.fixes[0] : undefined;
206
+ return form === undefined ? [] : [{ title: action.title, edits: form.edits }];
189
207
  });
190
208
  },
191
209
  inlayHints(file, enabled = () => true) {
@@ -202,6 +220,10 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
202
220
  .sort((a, b) => a.offset - b.offset || (a.label < b.label ? -1 : a.label > b.label ? 1 : 0));
203
221
  },
204
222
  tokens(file) {
223
+ // No plugin colours anything: answered without building or binding a program (an editor
224
+ // asks for tokens as soon as a file opens, before the first check has built one).
225
+ if (!config.plugins.some((plugin) => plugin.editor?.tokens !== undefined))
226
+ return [];
205
227
  const found = lookup(file);
206
228
  if (found === undefined)
207
229
  return [];
package/dist/config.js CHANGED
@@ -78,6 +78,7 @@ const isSummarize = (value) => typeof value === "function";
78
78
  const isSilentReason = (value) => typeof value === "function";
79
79
  const isHover = (value) => typeof value === "function";
80
80
  const isInlayHints = (value) => typeof value === "function";
81
+ const isGuarantees = (value) => typeof value === "function";
81
82
  const isCodeActions = (value) => typeof value === "function";
82
83
  const isTokens = (value) => typeof value === "function";
83
84
  const isLibraryFacts = (value) => typeof value === "function";
@@ -200,6 +201,19 @@ function parseMeta(value, where, errors) {
200
201
  return undefined;
201
202
  return { ...info, explain: value.explain };
202
203
  }
204
+ /** `RuleInfo.needsTypes` as given: undefined when left out, "invalid" when not a `LibraryTypes`. */
205
+ function parseNeedsTypes(value) {
206
+ if (value === undefined)
207
+ return undefined;
208
+ if (!isRecord(value))
209
+ return "invalid";
210
+ const { library, modules } = value;
211
+ if (typeof library !== "string" || library === "")
212
+ return "invalid";
213
+ if (!isStringArray(modules) || modules.length === 0)
214
+ return "invalid";
215
+ return { library, modules: [...modules] };
216
+ }
203
217
  /** The metadata a pack declares up front (`RuleInfo`): everything but the `explain` text. */
204
218
  function parseInfo(value, where, errors) {
205
219
  const found = parseInfoFields(value, where, errors);
@@ -211,12 +225,29 @@ function parseInfo(value, where, errors) {
211
225
  errors.push(`${where}.meta.sharedOptions must map option names to rule keys of the same pack`);
212
226
  return undefined;
213
227
  }
214
- const info = shared === undefined
228
+ const sharing = shared === undefined
215
229
  ? found
216
230
  : {
217
231
  ...found,
218
232
  sharedOptions: Object.fromEntries(Object.entries(shared).map(([name, rule]) => [name, String(rule)])),
219
233
  };
234
+ const { fixNeedsStrictNulls } = value;
235
+ const needsTypes = parseNeedsTypes(value.needsTypes);
236
+ if (needsTypes === "invalid") {
237
+ errors.push(`${where}.meta.needsTypes must be { library: "<name>", modules: ["<module>", …] } when present`);
238
+ return undefined;
239
+ }
240
+ if (fixNeedsStrictNulls !== undefined && fixNeedsStrictNulls !== true) {
241
+ errors.push(`${where}.meta.fixNeedsStrictNulls must be true when present`);
242
+ return undefined;
243
+ }
244
+ const typed = needsTypes === undefined
245
+ ? sharing
246
+ : {
247
+ ...sharing,
248
+ needsTypes,
249
+ };
250
+ const info = fixNeedsStrictNulls === true ? { ...typed, fixNeedsStrictNulls: true } : typed;
220
251
  if (value.options === undefined)
221
252
  return info;
222
253
  const options = parseOptionSpecs(value.options, where, errors);
@@ -227,12 +258,16 @@ function parseInfoFields(value, where, errors) {
227
258
  errors.push(`${where}.meta must be an object`);
228
259
  return undefined;
229
260
  }
230
- const { description, defaultSeverity, tier, group, addon, heuristic, widenedBy } = value;
261
+ const { description, summary, defaultSeverity, tier, group, addon, heuristic, widenedBy } = value;
231
262
  const { needsJsDoc, listUnknowns, yieldsTo } = value;
232
263
  if (typeof description !== "string") {
233
264
  errors.push(`${where}.meta.description must be a string`);
234
265
  return undefined;
235
266
  }
267
+ if (summary !== undefined && typeof summary !== "string") {
268
+ errors.push(`${where}.meta.summary must be a string when present`);
269
+ return undefined;
270
+ }
236
271
  if (!isSeverity(defaultSeverity)) {
237
272
  errors.push(`${where}.meta.defaultSeverity must be "error", "warning" or "info"`);
238
273
  return undefined;
@@ -257,7 +292,8 @@ function parseInfoFields(value, where, errors) {
257
292
  errors.push(`${where}.meta.group must name the rule's group in kebab-case, e.g. "switches"`);
258
293
  return undefined;
259
294
  }
260
- const base = { description, defaultSeverity, tier, group };
295
+ const described = { description, defaultSeverity, tier, group };
296
+ const base = summary === undefined ? described : { ...described, summary };
261
297
  const guessed = heuristic === true ? { ...base, heuristic: true } : base;
262
298
  const reading = needsJsDoc === true ? { ...guessed, needsJsDoc: true } : guessed;
263
299
  const listing = listUnknowns === true ? { ...reading, listUnknowns: true } : reading;
@@ -329,7 +365,7 @@ function parseEditor(value, where, errors) {
329
365
  errors.push(`${where}.editor must be an object`);
330
366
  return undefined;
331
367
  }
332
- const { hover, tokens, libraryFacts, inlayHints, codeActions } = value;
368
+ const { hover, tokens, libraryFacts, inlayHints, codeActions, guarantees } = value;
333
369
  const editor = {};
334
370
  if (codeActions !== undefined) {
335
371
  if (!isCodeActions(codeActions)) {
@@ -352,6 +388,13 @@ function parseEditor(value, where, errors) {
352
388
  }
353
389
  editor.libraryFacts = libraryFacts;
354
390
  }
391
+ if (guarantees !== undefined) {
392
+ if (!isGuarantees(guarantees)) {
393
+ errors.push(`${where}.editor.guarantees must be a function`);
394
+ return undefined;
395
+ }
396
+ editor.guarantees = guarantees;
397
+ }
355
398
  if (hover !== undefined) {
356
399
  if (!isHover(hover)) {
357
400
  errors.push(`${where}.editor.hover must be a function`);