@stateward/core 1.1.0 → 1.2.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/dist/rollout.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { ruleIds } from "./severity.js";
4
+ import { renamedRule } from "./renamed.js";
4
5
  export const ROLLOUT_FILE = "stateward.rollout.json";
5
6
  const ROLLOUT_VERSION = 1;
6
7
  /**
@@ -58,7 +59,8 @@ function parseEnabled(text, file, known) {
58
59
  const seen = new Set();
59
60
  const kept = [];
60
61
  for (const listed of enabled) {
61
- const id = listed;
62
+ // A renamed rule is read under its new id; the next write saves that one.
63
+ const id = known.has(listed) ? listed : (renamedRule(listed) ?? listed);
62
64
  if (!known.has(id)) {
63
65
  throw broken(file, `lists "${id}", which is not a rule of your packs`, `remove "${id}" from its "enabled" list; the other rules stay on`);
64
66
  }
package/dist/testing.js CHANGED
@@ -86,14 +86,18 @@ const MIN_EXAMPLE_INDENT = 4;
86
86
  function withoutNames(line) {
87
87
  return line.replace(/`[^`]*`/g, "");
88
88
  }
89
- /** A hint is one line, or one line and an indented code example of up to four lines. */
90
- function hintProblems(hint) {
91
- const [first = "", ...example] = hint.split(/\r?\n/);
92
- const problems = lineProblems("fix hint", first, undefined);
93
- const words = withoutNames(first);
94
- if (words.length > MAX_HINT_LENGTH) {
95
- problems.push(`fix hint words are ${String(words.length)} characters without its names; at most ${String(MAX_HINT_LENGTH)}`);
96
- }
89
+ /** The words of one line of a fix, its names left out, must fit the fix line's limit. */
90
+ function wordsProblems(label, line) {
91
+ const words = withoutNames(line);
92
+ return words.length > MAX_HINT_LENGTH
93
+ ? [
94
+ `${label} words are ${String(words.length)} characters without its names; at most ${String(MAX_HINT_LENGTH)}`,
95
+ ]
96
+ : [];
97
+ }
98
+ /** A code example: up to four lines, each indented 4 spaces and at most 100 characters. */
99
+ function exampleProblems(example) {
100
+ const problems = [];
97
101
  if (example.length > MAX_EXAMPLE_LINES) {
98
102
  problems.push(`fix hint example has ${String(example.length)} lines; at most ${String(MAX_EXAMPLE_LINES)}`);
99
103
  }
@@ -107,6 +111,42 @@ function hintProblems(hint) {
107
111
  }
108
112
  return problems;
109
113
  }
114
+ /**
115
+ * A hint is one line, or one line and an indented code example of up to four lines (M2). With
116
+ * several ways to fix (M22) it is `one of`, then one `- ` line per way, each starting with its
117
+ * action in lowercase and every one after the first with `or`, each with its own example.
118
+ */
119
+ function hintProblems(hint) {
120
+ const [first = "", ...rest] = hint.split(/\r?\n/);
121
+ const problems = lineProblems("fix hint", first, undefined);
122
+ problems.push(...wordsProblems("fix hint", first));
123
+ if (!rest.some((line) => line.startsWith("- ")))
124
+ return [...problems, ...exampleProblems(rest)];
125
+ if (first !== "one of")
126
+ problems.push('a fix hint with ways to fix must start with "one of"');
127
+ const ways = [];
128
+ for (const line of rest) {
129
+ const last = ways.at(-1);
130
+ if (line.startsWith("- "))
131
+ ways.push({ line, example: [] });
132
+ else if (last === undefined)
133
+ problems.push(`fix hint line "${line}" must follow a way to fix`);
134
+ else
135
+ last.example.push(line);
136
+ }
137
+ if (ways.length < 2)
138
+ problems.push('a fix hint with "one of" needs two ways to fix or more');
139
+ ways.forEach((way, index) => {
140
+ const text = way.line.slice(2);
141
+ problems.push(...wordsProblems("fix hint way", text), ...exampleProblems(way.example));
142
+ if (!/^[a-z]/.test(text))
143
+ problems.push(`fix hint way "${text}" must start in lowercase`);
144
+ if (index > 0 && !/^or\b/.test(text)) {
145
+ problems.push(`fix hint way "${text}" must start with "or"`);
146
+ }
147
+ });
148
+ return problems;
149
+ }
110
150
  function lineProblems(label, text, maxLength) {
111
151
  const problems = [];
112
152
  if (text.trim().length === 0)
package/dist/types.d.ts CHANGED
@@ -379,7 +379,9 @@ export type TypeQueries = {
379
379
  * `"not-object"` for a primitive, a union, an array, a tuple or an array-like (a number index and a numeric `length`, such as
380
380
  * `RegExpMatchArray`): the rules that ask do not apply.
381
381
  * `"generic"` when the keys depend on a type parameter (`Record<K, string>`, `{ [P in K]: n }`):
382
- * the properties are not known until `K` is, so the type has no key list to judge.
382
+ * the properties are not known until `K` is, so the type has no key list to judge. Also when a
383
+ * mapped type takes its keys from a type that does not resolve (`keyof typeof NAMES` from a
384
+ * package that is not installed): TypeScript then gives it an index signature for every key.
383
385
  */
384
386
  propertyKeysOf(node: ts.Node): {
385
387
  required: readonly string[];
@@ -403,6 +405,19 @@ export type TypeQueries = {
403
405
  isDiscriminant(object: ts.Node, propertyName: string): boolean;
404
406
  /** The type of an expression as TypeScript prints it, on one line (`Record<string, string>`). */
405
407
  typeTextOf(node: ts.Node): string;
408
+ /**
409
+ * Whether two expressions have the same type: each is assignable to the other. Two types that
410
+ * print the same name (a local `Phase` and an imported one) can differ; this compares the types.
411
+ * False when either is `any`, written or from a type that does not resolve.
412
+ */
413
+ sameType(a: ts.Node, b: ts.Node): boolean;
414
+ /**
415
+ * Whether the type an object declares for the entry an element access reads, before any
416
+ * narrowing, already admits a missing value: `unknown`, `any`, or a union with `undefined`
417
+ * (`Record<string, unknown>`). TypeScript then makes the code check the value before using it.
418
+ * False when the entry's declared type cannot be found.
419
+ */
420
+ declaredEntryCanBeMissing(access: ts.ElementAccessExpression): boolean;
406
421
  /**
407
422
  * The type the surrounding code expects for an expression, as `typeTextOf` prints it: for a
408
423
  * function written as a JSX attribute, the declared type of that prop (`() => Promise<void>`);
@@ -430,16 +445,73 @@ export type TypeQueries = {
430
445
  */
431
446
  uniqueSymbolKeyFiles(node: ts.Node): readonly string[];
432
447
  /**
433
- * The guarantees a type states: the string literals of its optional `__guarantee` property
434
- * (`Context<T> & { readonly __guarantee?: "required-context" }`), sorted. The type is the one
435
- * of an expression or type node, or the declared type of a symbol (a variable's type, a type
436
- * alias's type), resolved through aliases, generics and re-exports. A type parameter is widened
437
- * to its constraint; `null` and `undefined` members are left out, and every other member of a
438
- * union must state a guarantee for it to count. Empty for a type that states none, or whose
439
- * `__guarantee` is required or not a string literal (that is a brand, not a guarantee). The
448
+ * The guarantees a type states: one name per optional `"__guarantee:<name>"` property
449
+ * (`Context<T> & { readonly "__guarantee:required-context"?: true }`), and the string literals of
450
+ * an optional `__guarantee` property (the 1.1.0 form, `{ readonly __guarantee?: "owned" }`),
451
+ * sorted. Traits combine by intersection: `Owned<Opaque<string, "Id">>` gives both. The type is
452
+ * the one of an expression or type node, or the declared type of a symbol (a variable's type, a
453
+ * type alias's type), resolved through aliases, generics and re-exports. A type parameter is
454
+ * widened to its constraint; `null` and `undefined` members are left out, and every other member
455
+ * of a union must state a guarantee for it to count. A required marker property, or a 1.1.0
456
+ * `__guarantee` that is not string literals, states none (that is a brand, not a guarantee). The
440
457
  * names mean nothing to core; each plugin reads its own.
441
458
  */
442
459
  guaranteesOf(target: ts.Node | SymbolRef): readonly string[];
460
+ /**
461
+ * The guarantees of the type the surrounding code expects for an expression (as
462
+ * `contextualTypeTextOf`), read as `guaranteesOf` reads a type: `{ … }` returned from a function
463
+ * typed `OrderId`, or passed to a parameter of that type. Empty when nothing is expected.
464
+ */
465
+ contextualGuaranteesOf(node: ts.Expression): readonly string[];
466
+ /**
467
+ * The values a trait's marker property holds, sorted: `"OrderId"` for
468
+ * `Opaque<string, "OrderId">`, `true` for `Pending<boolean>`, `"saving"` for
469
+ * `Pending<Status, "saving">`. Read from the type of the node, of the symbol's declaration, or,
470
+ * with `contextual`, of the type the surrounding code expects for the expression. Undefined when
471
+ * the type does not state the trait; `"not-finite"` when the property's type is not literals.
472
+ */
473
+ guaranteeValuesOf(target: ts.Node | SymbolRef, name: string, contextual?: boolean): readonly Literal[] | "not-finite" | undefined;
474
+ /**
475
+ * How a value is disposed when its type is a standard `Disposable` or `AsyncDisposable`: it has
476
+ * a `[Symbol.dispose]` (`"sync"`) or `[Symbol.asyncDispose]` (`"async"`) method, declared in
477
+ * `file`. Undefined for any other type, and for `any`.
478
+ */
479
+ disposeOf(node: ts.Node): {
480
+ readonly kind: "sync" | "async";
481
+ readonly file: string;
482
+ } | undefined;
483
+ /**
484
+ * The type alias the surrounding code expects for an expression (`OrderId` for an argument of
485
+ * `save(id: OrderId)`; `OrderId | undefined` gives `OrderId`), as a symbol whose declaration
486
+ * `declarationOf` finds. Undefined when nothing is expected, the type is not one alias, or the
487
+ * alias is generic.
488
+ */
489
+ contextualAliasOf(node: ts.Expression): SymbolRef | undefined;
490
+ /**
491
+ * The property a name destructured from an object reads: `cacheEntryRemoved` of the
492
+ * parameter's type for `{ cacheEntryRemoved }`, as a symbol whose declaration `declarationOf`
493
+ * finds. Undefined for a rest element, an array pattern, a computed key, or a type with no such
494
+ * property.
495
+ */
496
+ bindingPropertyOf(element: ts.BindingElement): SymbolRef | undefined;
497
+ /**
498
+ * Whether any file of the program (the project's or a package's) writes the marker property of
499
+ * a trait, `"__guarantee:<name>"`: a rule skips work for a trait nobody states.
500
+ */
501
+ declaresTrait(name: string): boolean;
502
+ /**
503
+ * Whether a file of the project declares a member named `[Symbol.dispose]` or
504
+ * `[Symbol.asyncDispose]` (a class, an interface, a type or an object literal), read from the
505
+ * syntax once per program: only such a member states the release trait by its type.
506
+ */
507
+ declaresDispose(): boolean;
508
+ /**
509
+ * The other names the project's files give a binding, by the name they rename: `onSnapshot` →
510
+ * `listen` for `import { onSnapshot as listen }`, `export { onSnapshot as listen }`,
511
+ * `const listen = onSnapshot` (or `= db.onSnapshot`) and `const { onSnapshot: listen } = db`.
512
+ * Read from the syntax once per program.
513
+ */
514
+ renamedBindings(): ReadonlyMap<string, ReadonlySet<string>>;
443
515
  /**
444
516
  * The type alias a value's type is an instance of, found from its declaration: after awaiting a
445
517
  * `Promise`, every member of the type must be written in the same alias (`Result<T, E>` and
@@ -454,11 +526,13 @@ export type TypeQueries = {
454
526
  /**
455
527
  * The type alias that names the type of an expression as written (`TouchpointStatus` for
456
528
  * `touchpointStatus()` declared to return it; a type parameter widened to its constraint), or
457
- * undefined when the type has no alias or the alias takes type arguments.
529
+ * undefined when the type has no alias or the alias takes type arguments. `declaration` is the
530
+ * alias's declaration.
458
531
  */
459
532
  typeAliasOf(node: ts.Node): {
460
533
  readonly name: string;
461
534
  readonly file: string;
535
+ readonly declaration: ts.TypeAliasDeclaration;
462
536
  } | undefined;
463
537
  /**
464
538
  * Where `fromFile` would import the type alias `name` declared in `file` from, written as
@@ -646,6 +720,15 @@ export type TypeQueries = {
646
720
  * takes one, the call does not resolve, or the parameter is a rest parameter.
647
721
  */
648
722
  signalParameterOf(call: ts.CallExpression): SignalParameter | undefined;
723
+ /**
724
+ * Whether TypeScript reports that the end of a function can be reached although the function
725
+ * must return a value: TS2366 (the return type does not include `undefined`), TS2355 (a
726
+ * declared type that is not `void`, `any` or `undefined`), TS2534 (a function returning
727
+ * `never`) or TS7030 (`noImplicitReturns`: not all code paths return a value). Only the errors
728
+ * TypeScript reports on the function itself (its name, signature or return type) count, not
729
+ * those in its body. Asks for the type errors of the function's file, once per file.
730
+ */
731
+ reportsReachableEnd(fn: ts.FunctionLikeDeclaration): boolean;
649
732
  };
650
733
  export type ReportProblem = {
651
734
  message: string;
@@ -660,6 +743,12 @@ export type ReportProblem = {
660
743
  * finding's kind (`option.severities`) still wins over it.
661
744
  */
662
745
  severity?: "info" | "warning";
746
+ /**
747
+ * The finding is against a guarantee the code states (`Pending<T>`, `Owned<T>`): proven strictly,
748
+ * so it is an error while the rule is on, even for a heuristic rule whose shape-based findings
749
+ * are warnings. A severity the config gives this finding's kind still wins over it.
750
+ */
751
+ stated?: true;
663
752
  related?: readonly {
664
753
  node: ts.Node;
665
754
  message: string;
@@ -681,6 +770,21 @@ export type ReportProblem = {
681
770
  export type FunctionFacts = {
682
771
  readonly throws?: readonly string[];
683
772
  readonly rejects?: readonly string[];
773
+ /** What the call returns must be released (the release trait): how it is released. */
774
+ readonly returns?: ReleaseFact;
775
+ /**
776
+ * The promise never rejects: the function's result, or the property itself for a promise
777
+ * property (RTK Query's `cacheEntryRemoved`). An `await` of it is not a way out.
778
+ */
779
+ readonly neverRejects?: true;
780
+ };
781
+ /**
782
+ * How a value with the release trait is released, as a `facts` line says it: `"release"`, call the
783
+ * returned function (`onSnapshot`'s unsubscribe); `{ release: "unsubscribe" }`, call that method
784
+ * on the returned value (RxJS's `Subscription`).
785
+ */
786
+ export type ReleaseFact = "release" | {
787
+ readonly release: string;
684
788
  };
685
789
  export type PackageFactsConfig = Readonly<Record<string, Readonly<Record<string, FunctionFacts>>>>;
686
790
  /** Where a library fact comes from, in order of trust. */
@@ -699,6 +803,14 @@ export type LibraryUse = {
699
803
  readonly unknown: readonly string[];
700
804
  }[];
701
805
  };
806
+ /**
807
+ * The noun for the places a guarantee covers, both forms written out ("switch", "switches"): a
808
+ * plural is never made by adding "s".
809
+ */
810
+ export type CoveredNoun = {
811
+ readonly one: string;
812
+ readonly many: string;
813
+ };
702
814
  /** A place a stated guarantee covers: a reader of a required context, a writer of owned state. */
703
815
  export type CoveredPlace = {
704
816
  /** How the place is named in a list: `<Profile>`, `useTheme()`. */
@@ -709,11 +821,31 @@ export type CoveredPlace = {
709
821
  * A guarantee stated in the project's code, as the plugin that proves it reads it
710
822
  * (`EditorContributions.guarantees`): for `stateward guarantees` and the editor's hover and code
711
823
  * lens. Whether it is proven is not said here: core counts the findings of `ruleId` that name the
712
- * declaration (a related note at `location`), so the list and the check never disagree.
824
+ * declaration (a related note at `location`) or lie in a place it covers, so the list and the
825
+ * check never disagree.
713
826
  */
827
+ /**
828
+ * Where a trait is stated: a standard type that already says it (`Disposable`), the project's
829
+ * marker type (`Owned<T>`), the config's `facts` line for a package, or the facts a plugin ships
830
+ * for it (stateward's facts).
831
+ */
832
+ export type TraitSource = {
833
+ readonly kind: "type";
834
+ readonly name: string;
835
+ } | {
836
+ readonly kind: "marker";
837
+ } | {
838
+ readonly kind: "config";
839
+ readonly package: string;
840
+ } | {
841
+ readonly kind: "shipped";
842
+ readonly package: string;
843
+ };
714
844
  export type StatedGuarantee = {
715
- /** The guarantee's name, as `__guarantee` writes it: `required-context`. */
845
+ /** The guarantee's name, as its marker property writes it: `required-context`. */
716
846
  readonly guarantee: string;
847
+ /** Where the trait is stated; a marker when not given. */
848
+ readonly source?: TraitSource;
717
849
  /** The marker type as the declaration's type names it: `RequiredContext`. */
718
850
  readonly marker: string;
719
851
  /** The declaration that states it: `ThemeContext`. */
@@ -727,8 +859,8 @@ export type StatedGuarantee = {
727
859
  readonly ruleId: string;
728
860
  /** What it promises, after "Guaranteed: ": "every reader is rendered under its Provider". */
729
861
  readonly promise: string;
730
- /** What `covered` holds, as a plural noun: "readers", "writers". */
731
- readonly covers: string;
862
+ /** What `covered` holds, as a noun in both forms: `{ one: "switch", many: "switches" }`. */
863
+ readonly covers: CoveredNoun;
732
864
  /** The places the proof covers, in file and offset order; empty when nothing uses it. */
733
865
  readonly covered: readonly CoveredPlace[];
734
866
  };
@@ -736,6 +868,11 @@ export type FileContext<O extends Options = Options> = {
736
868
  readonly file: string;
737
869
  /** The config's facts about packages (`facts`); `{}` when it gives none. */
738
870
  readonly facts: PackageFactsConfig;
871
+ /**
872
+ * The facts the loaded plugins ship for common packages (`Plugin.facts`), joined in plugin
873
+ * order. The config's own `facts` line for a function wins over a shipped one.
874
+ */
875
+ readonly shippedFacts: PackageFactsConfig;
739
876
  /** The rule's options: the config's values with the defaults filled in; `{}` when it declares none. */
740
877
  readonly options: O;
741
878
  readonly sourceFile: ts.SourceFile;
@@ -774,6 +911,13 @@ export type FileRule<S extends OptionSpecs = OptionSpecs, G extends string = str
774
911
  kind: "file";
775
912
  meta: RuleMeta<S, G>;
776
913
  check(ctx: FileContext<OptionsOf<S>>): void;
914
+ /**
915
+ * What the plugin's editor contributions read of this file (`EditorContributions.guarantees`,
916
+ * `hover`), as JSON: run after `check` on the same file, cached with its findings, and handed
917
+ * out by `projectSummaries` like a project rule's. It decides no finding: the findings are
918
+ * `check`'s alone, so the editor's fast pass stays complete without it.
919
+ */
920
+ summarize?(ctx: FileContext<OptionsOf<S>>): Json | undefined;
777
921
  };
778
922
  export type ProjectRule<Summary extends Json = Json, S extends OptionSpecs = OptionSpecs, G extends string = string> = {
779
923
  kind: "project";
@@ -910,6 +1054,12 @@ export type Plugin = {
910
1054
  description: string;
911
1055
  rules: Readonly<Record<string, PluginRule>>;
912
1056
  editor?: EditorContributions;
1057
+ /**
1058
+ * Facts about common packages that the plugin ships (stateward's facts), in the config's
1059
+ * `facts` shape: `{ rxjs: { "Observable.subscribe": { returns: { release: "unsubscribe" } } } }`.
1060
+ * Every rule reads them as `FileContext.shippedFacts`; the config's facts win over them.
1061
+ */
1062
+ facts?: PackageFactsConfig;
913
1063
  };
914
1064
  /** A plugin that keeps its literal name and rule keys, as `definePlugin` returns it. */
915
1065
  export type PluginOf<N extends string, R extends Readonly<Record<string, PluginRule>>> = {
@@ -917,6 +1067,7 @@ export type PluginOf<N extends string, R extends Readonly<Record<string, PluginR
917
1067
  description: string;
918
1068
  rules: R;
919
1069
  editor?: EditorContributions;
1070
+ facts?: PackageFactsConfig;
920
1071
  };
921
1072
  /** Every rule id ("<plugin>/<rule key>") a plugin type offers; any string pair for a wide `Plugin`. */
922
1073
  export type RuleIdOf<P extends Plugin> = P extends Plugin ? `${P["name"]}/${Extract<keyof P["rules"], string>}` : never;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stateward/core",
3
- "version": "1.1.0",
3
+ "version": "1.2.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": {