@stateward/core 1.0.1-rc.1 → 1.0.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.
package/README.md CHANGED
@@ -1,12 +1,88 @@
1
1
  # @stateward/core
2
2
 
3
3
  The engine of [stateward](https://github.com/khoing1111/ts-stateward#readme) and the API for
4
- writing rules: `defineRule`, `definePlugin`, `option`, and test helpers in
5
- `@stateward/core/testing`. `stateward` installs it; add it yourself only to write a rule.
4
+ writing rules of your own: a convention your team keeps that no pack checks (a limit, a naming
5
+ rule, a call nobody should make). Your rule lives next to your code, loads from
6
+ `stateward.config.ts`, and reports in the terminal, in CI and in VS Code like any bundled rule.
7
+
8
+ `stateward` installs this package; add it yourself only to write a rule, at the same version as
9
+ `stateward`:
6
10
 
7
11
  ```bash
8
12
  npm install --save-dev @stateward/core
9
13
  ```
10
14
 
11
- How to write, load and test a rule:
12
- [docs/user/write-your-own-rule.md](https://github.com/khoing1111/ts-stateward/blob/main/docs/user/write-your-own-rule.md).
15
+ ## What it exports
16
+
17
+ - `defineRule`, `definePlugin` and `option`: a rule, the plugin that holds it, and its options.
18
+ - `@stateward/core/typescript`: the TypeScript that stateward reads with. Import it, never your
19
+ app's `typescript`.
20
+ - `@stateward/core/testing`: `checkFixture` to run a rule on a small project in a test, and
21
+ `expectMessageStandard` to check its messages.
22
+
23
+ ## Example
24
+
25
+ A rule that warns when a union has more members than the team allows:
26
+
27
+ ```ts
28
+ // stateward-rules/team.ts
29
+ import ts from "@stateward/core/typescript";
30
+ import { definePlugin, defineRule, option } from "@stateward/core";
31
+
32
+ export const maxUnionMembers = defineRule({
33
+ kind: "file", // one file at a time; "project" looks across files
34
+ meta: {
35
+ description: "A type alias whose union has more members than the team's limit.",
36
+ defaultSeverity: "warning",
37
+ tier: "core",
38
+ group: "unions",
39
+ options: {
40
+ max: option.number({ default: 12, min: 1, integer: true, description: "Most members." }),
41
+ },
42
+ explain: "# team/max-union-members\n…", // the page `stateward explain` shows
43
+ },
44
+ check(ctx) {
45
+ const visit = (node: ts.Node): void => {
46
+ if (ts.isTypeAliasDeclaration(node) && ts.isUnionTypeNode(node.type)) {
47
+ const count = node.type.types.length;
48
+ if (count > ctx.options.max) {
49
+ ctx.report({
50
+ node: node.name,
51
+ message: `\`${node.name.text}\` has ${String(count)} members; above ${String(ctx.options.max)}, switches over it get hard to keep complete`,
52
+ hint: "split it into nested unions by kind",
53
+ });
54
+ }
55
+ }
56
+ ts.forEachChild(node, visit);
57
+ };
58
+ visit(ctx.sourceFile);
59
+ },
60
+ });
61
+
62
+ export const team = definePlugin({
63
+ name: "team",
64
+ description: "This team's own rules.",
65
+ rules: { "max-union-members": maxUnionMembers },
66
+ });
67
+ ```
68
+
69
+ Load it in `stateward.config.ts`; the rule's id is the plugin's name, a slash, and its key:
70
+
71
+ ```ts
72
+ import { defineConfig } from "stateward";
73
+ import { team } from "./stateward-rules/team.js";
74
+
75
+ export default defineConfig({
76
+ plugins: [team],
77
+ rules: { "team/max-union-members": ["warning", { max: 12 }] },
78
+ });
79
+ ```
80
+
81
+ Then `npx stateward check --rule team/max-union-members`.
82
+
83
+ ## Docs
84
+
85
+ - [Write a rule of your own](https://github.com/khoing1111/ts-stateward/blob/main/docs/user/write-your-own-rule.md):
86
+ options, tests, messages, quick fixes, and what to do when the rule cannot tell.
87
+ - [The bundled rules](https://github.com/khoing1111/ts-stateward/blob/main/docs/rules/README.md):
88
+ check them first; what you want may be an option of one.
@@ -625,21 +625,6 @@ shared = isLibraryFile) {
625
625
  },
626
626
  };
627
627
  }
628
- /**
629
- * The host a recorded program is replayed against: the disk, with `overlays` in front of it as
630
- * `hostWithOverlays` serves them (an overlay exists, and its text is what is read), so a replay
631
- * answers as the build it stands for would have.
632
- */
633
- function replayHost(options, overlays) {
634
- const base = ts.createCompilerHost(options, false);
635
- if (overlays.size === 0)
636
- return base;
637
- return {
638
- ...base,
639
- fileExists: (fileName) => overlays.has(fileName) || base.fileExists(fileName),
640
- readFile: (fileName) => overlays.get(fileName) ?? base.readFile(fileName),
641
- };
642
- }
643
628
  function matcher(patterns) {
644
629
  if (patterns.length === 0)
645
630
  return () => false;
@@ -1624,10 +1609,8 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1624
1609
  if (missingLib !== undefined)
1625
1610
  throw new TypeScriptLibMissingError(missingLib);
1626
1611
  // Only a program built from nothing asks the host every question; one built on an old
1627
- // program is not recorded. One built on unsaved text is: its answers are the overlays', and a
1628
- // replay serves the overlays of its own run the same way (`replayHost`), so the record holds
1629
- // exactly while the open documents have that text (an editor's next start).
1630
- const queries = cache !== undefined && oldProgram === undefined && !trustCache
1612
+ // program, or on unsaved text, is not recorded.
1613
+ const queries = cache !== undefined && oldProgram === undefined && overlays.size === 0 && !trustCache
1631
1614
  ? new Map()
1632
1615
  : undefined;
1633
1616
  const plainHost = hostWithOverlays(parsed.options, overlays, sources, trustCache, jsDoc);
@@ -1722,9 +1705,9 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1722
1705
  * now: its files and fingerprints come from the record, and the program is built only if
1723
1706
  * something asks for a node or a type.
1724
1707
  */
1725
- const recordedUnit = (project, claimed, record, overlays) => {
1708
+ const recordedUnit = (project, claimed, record) => {
1726
1709
  let built;
1727
- const real = () => (built ??= buildUnit(project, claimed, overlays, false));
1710
+ const real = () => (built ??= buildUnit(project, claimed, new Map(), false));
1728
1711
  return {
1729
1712
  tsconfig: project.tsconfigPath,
1730
1713
  files: record.files,
@@ -1755,12 +1738,13 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
1755
1738
  const record = cache?.programs.get(project.tsconfigPath);
1756
1739
  const replayable = record !== undefined &&
1757
1740
  !previous.has(project.tsconfigPath) &&
1741
+ normalized.size === 0 &&
1758
1742
  !trustCache &&
1759
1743
  record.inputs ===
1760
1744
  recordInputs(programInputs(project.parsed, claimed), project.parsed.options) &&
1761
- replays(record.queries, replayHost(project.parsed.options, normalized));
1745
+ replays(record.queries, ts.createCompilerHost(project.parsed.options, false));
1762
1746
  return replayable
1763
- ? recordedUnit(project, claimed, record, normalized)
1747
+ ? recordedUnit(project, claimed, record)
1764
1748
  : buildUnit(project, claimed, normalized, trustCache);
1765
1749
  });
1766
1750
  };
package/dist/checker.d.ts CHANGED
@@ -65,14 +65,8 @@ 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.
74
68
  */
75
- checkFiles(files: readonly string[], overlays?: ReadonlyMap<string, string>, reusable?: readonly string[]): CheckResult;
69
+ checkFiles(files: readonly string[], overlays?: ReadonlyMap<string, string>): CheckResult;
76
70
  /** Ids of the active project rules, whose findings only `check` produces. */
77
71
  readonly projectRuleIds: ReadonlySet<string>;
78
72
  /**
package/dist/checker.js CHANGED
@@ -109,14 +109,12 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
109
109
  sliceStarted = performance.now();
110
110
  }
111
111
  },
112
- checkFiles(files, overlays = new Map(), reusable = []) {
112
+ checkFiles(files, overlays = new Map()) {
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, cache === false || reusable.length === 0
118
- ? undefined
119
- : { cache, files: new Set(reusable.map(toTypeScriptPath)) });
117
+ return runFileRules(config, cwd, units, new Set(files.map(toTypeScriptPath)), started, uncapped === undefined, ignores !== false);
120
118
  },
121
119
  // Read on demand: it consults the rollout file, which a run that ignores rollout
122
120
  // (`plan`, `check --rule`) must not touch.
@@ -204,10 +202,6 @@ export function createChecker({ config, cwd, rules = { kind: "configured" }, cac
204
202
  .sort((a, b) => a.offset - b.offset || (a.label < b.label ? -1 : a.label > b.label ? 1 : 0));
205
203
  },
206
204
  tokens(file) {
207
- // No plugin colours anything: answered without building or binding a program (an editor
208
- // asks for tokens as soon as a file opens, before the first check has built one).
209
- if (!config.plugins.some((plugin) => plugin.editor?.tokens !== undefined))
210
- return [];
211
205
  const found = lookup(file);
212
206
  if (found === undefined)
213
207
  return [];
package/dist/engine.d.ts CHANGED
@@ -131,24 +131,12 @@ export declare function projectRuleIds(config: Config): ReadonlySet<string>;
131
131
  * rule id, from the summaries of a full check; rules with no reason are left out.
132
132
  */
133
133
  export declare function silentReasons(config: Config, selection: RuleSelection, summaries: ReadonlyMap<string, () => ReadonlyMap<string, Json>>): ReadonlyMap<string, string>;
134
- /**
135
- * What a fast pass may take from the cache instead of running the rules: the results the cache
136
- * holds for each of `files` whose dependency fingerprint and reads are as they were then (the
137
- * same test as a full pass's). Asking for a fingerprint computes those of the whole program
138
- * once, so a caller names only the files it expects to be unchanged (an editor's file just opened).
139
- */
140
- export type FastReuse = {
141
- readonly cache: ResultCache;
142
- readonly files: ReadonlySet<string>;
143
- };
144
134
  /**
145
135
  * Runs the file rules (not the project rules) over the own files of `units` that are in `files`
146
136
  * and returns findings for those files only. A project rule needs every file's summary, so it
147
- * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`. With `reuse`, a
148
- * rule whose result the cache holds for a reusable file is not run (`FastReuse`): an unchanged
149
- * file costs no type checking.
137
+ * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`.
150
138
  */
151
- export declare function runFileRules(config: Config, cwd: string, units: readonly ProjectUnit[], files: ReadonlySet<string>, started: number, capped?: boolean, ignores?: boolean, reuse?: FastReuse): CheckResult;
139
+ export declare function runFileRules(config: Config, cwd: string, units: readonly ProjectUnit[], files: ReadonlySet<string>, started: number, capped?: boolean, ignores?: boolean): CheckResult;
152
140
  /**
153
141
  * The markdown behind `stateward explain`, or undefined for an unknown rule id. A lazy rule's
154
142
  * text is in its module, which is loaded for it.
package/dist/engine.js CHANGED
@@ -3,7 +3,7 @@ import { readRollout } from "./rollout.js";
3
3
  import { ruleKey, sha1, summaryOf, summaryValue } from "./cache.js";
4
4
  import { defaultOptions } from "./options.js";
5
5
  import { codeOf, loadRule } from "./lazy.js";
6
- import { IGNORE_EXPLAIN, IGNORE_RULE_ID, applyIgnores, fileDirectives } from "./ignores.js";
6
+ import { IGNORE_EXPLAIN, IGNORE_RULE_ID, applyIgnores, fileDirectives, readFileDirectives, } from "./ignores.js";
7
7
  import { addonsWith, appliedOverrides, ruleIsOn, ruleSetting, ruleSettingWith, } from "./severity.js";
8
8
  import { matchingOverrides } from "./overrides.js";
9
9
  import { defaults } from "./config.js";
@@ -853,27 +853,12 @@ export function silentReasons(config, selection, summaries) {
853
853
  }
854
854
  return reasons;
855
855
  }
856
- /** The cached results of `file` when its fingerprint and reads hold, else undefined. */
857
- function holdingResults(unit, file, cache) {
858
- const entry = cache.files.get(file);
859
- if (entry === undefined)
860
- return undefined;
861
- const fingerprint = unit.fingerprint(file);
862
- if (fingerprint === undefined || entry.fingerprint !== fingerprint)
863
- return undefined;
864
- if (!readsHold(unit, entry.reads))
865
- return undefined;
866
- // A copy: the fast pass never writes the cache (what it computes is for these files only).
867
- return new Map(entry.rules);
868
- }
869
856
  /**
870
857
  * Runs the file rules (not the project rules) over the own files of `units` that are in `files`
871
858
  * and returns findings for those files only. A project rule needs every file's summary, so it
872
- * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`. With `reuse`, a
873
- * rule whose result the cache holds for a reusable file is not run (`FastReuse`): an unchanged
874
- * file costs no type checking.
859
+ * does not run here. A rule that throws becomes a `failure`, as in `runFilePhase`.
875
860
  */
876
- export function runFileRules(config, cwd, units, files, started, capped = true, ignores = true, reuse) {
861
+ export function runFileRules(config, cwd, units, files, started, capped = true, ignores = true) {
877
862
  // The same rules a full pass runs (rollout included), so the fast pass never shows a rule
878
863
  // the developer has not turned on.
879
864
  const sets = ruleSets(config, { kind: "configured" });
@@ -885,33 +870,22 @@ export function runFileRules(config, cwd, units, files, started, capped = true,
885
870
  for (const file of unit.files) {
886
871
  if (!files.has(file))
887
872
  continue;
888
- const results = (reuse?.files.has(file) === true ? holdingResults(unit, file, reuse.cache) : undefined) ??
889
- new Map();
873
+ unit.bind();
874
+ const sourceFile = unit.sourceFile(file);
875
+ if (sourceFile === undefined)
876
+ continue;
890
877
  fileCount++;
891
- const syntax = results.get(SYNTAX_RULE_ID)?.findings ?? syntaxFinding(unit, file, cwd);
892
- const imports = results.get(IMPORTS_RULE_ID)?.findings ?? importsFinding(unit, file, cwd);
893
- findings.push(...syntax, ...imports);
878
+ findings.push(...syntaxFinding(unit, file, cwd), ...importsFinding(unit, file, cwd));
894
879
  if (ignores) {
895
- const read = fileDirectives(unit, file, results).directives;
880
+ const read = readFileDirectives(unit, file);
896
881
  if (read.length > 0)
897
882
  directives.set(file, read);
898
883
  }
899
884
  const startOfFile = { file, start: 0, end: 0 };
900
- let types;
885
+ const types = unit.typesFor(file);
901
886
  for (const entry of sets.forFile(file)) {
902
887
  if (entry.rule.kind !== "file")
903
888
  continue;
904
- const result = results.get(entry.key);
905
- if (result !== undefined) {
906
- findings.push(...result.findings);
907
- continue;
908
- }
909
- // Rules need parents: bind before the first one runs. A file whose results all come from
910
- // the cache asks nothing of the program (a recorded one is then never built).
911
- const sourceFile = boundSourceFile(unit, file);
912
- if (sourceFile === undefined)
913
- break;
914
- types ??= unit.typesFor(file);
915
889
  try {
916
890
  runFileSide(entry.rule, fileContext(entry, sourceFile, types, findings));
917
891
  }
package/dist/ignores.d.ts CHANGED
@@ -44,6 +44,8 @@ export declare function fileDirectives(unit: ProjectUnit, file: string, results:
44
44
  directives: readonly IgnoreDirective[];
45
45
  stored: boolean;
46
46
  };
47
+ /** The ignore comments of one file, read now (the fast pass has no cache to keep them in). */
48
+ export declare function readFileDirectives(unit: ProjectUnit, file: string): readonly IgnoreDirective[];
47
49
  /** The ids a comment may name, and the ones whose rule ran, for "nothing to ignore" to be a fair judgement. */
48
50
  export type IgnoreScope = {
49
51
  /** Every rule id of the config's plugins, and the ids stateward reports itself. */
package/dist/ignores.js CHANGED
@@ -233,6 +233,10 @@ export function fileDirectives(unit, file, results) {
233
233
  results.set(COMMENTS_KEY, { findings: [], summary: summaryOf(directives) });
234
234
  return { directives, stored: true };
235
235
  }
236
+ /** The ignore comments of one file, read now (the fast pass has no cache to keep them in). */
237
+ export function readFileDirectives(unit, file) {
238
+ return readDirectives(unit, file);
239
+ }
236
240
  function distance(a, b) {
237
241
  let previous = Array.from({ length: b.length + 1 }, (_, i) => i);
238
242
  for (let i = 1; i <= a.length; i++) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stateward/core",
3
- "version": "1.0.1-rc.1",
3
+ "version": "1.0.1",
4
4
  "description": "The engine of stateward (exclusive states and predictable code paths for TypeScript) and the API for writing your own rules and packs.",
5
5
  "license": "MIT",
6
6
  "repository": {